babylon.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183
  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. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * 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)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * 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)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * 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)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * 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)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * 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)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * 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)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * 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)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * 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)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * 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)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * 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.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. if (x === void 0) { x = 0; }
  2217. if (y === void 0) { y = 0; }
  2218. this.x = x;
  2219. this.y = y;
  2220. }
  2221. /**
  2222. * Gets a string with the Vector2 coordinates
  2223. * @returns a string with the Vector2 coordinates
  2224. */
  2225. Vector2.prototype.toString = function () {
  2226. return "{X: " + this.x + " Y:" + this.y + "}";
  2227. };
  2228. /**
  2229. * Gets class name
  2230. * @returns the string "Vector2"
  2231. */
  2232. Vector2.prototype.getClassName = function () {
  2233. return "Vector2";
  2234. };
  2235. /**
  2236. * Gets current vector hash code
  2237. * @returns the Vector2 hash code as a number
  2238. */
  2239. Vector2.prototype.getHashCode = function () {
  2240. var hash = this.x || 0;
  2241. hash = (hash * 397) ^ (this.y || 0);
  2242. return hash;
  2243. };
  2244. // Operators
  2245. /**
  2246. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2247. * @param array defines the source array
  2248. * @param index defines the offset in source array
  2249. * @returns the current Vector2
  2250. */
  2251. Vector2.prototype.toArray = function (array, index) {
  2252. if (index === void 0) { index = 0; }
  2253. array[index] = this.x;
  2254. array[index + 1] = this.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Copy the current vector to an array
  2259. * @returns a new array with 2 elements: the Vector2 coordinates.
  2260. */
  2261. Vector2.prototype.asArray = function () {
  2262. var result = new Array();
  2263. this.toArray(result, 0);
  2264. return result;
  2265. };
  2266. /**
  2267. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2268. * @param source defines the source Vector2
  2269. * @returns the current updated Vector2
  2270. */
  2271. Vector2.prototype.copyFrom = function (source) {
  2272. this.x = source.x;
  2273. this.y = source.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Sets the Vector2 coordinates with the given floats
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. * @returns the current updated Vector2
  2281. */
  2282. Vector2.prototype.copyFromFloats = function (x, y) {
  2283. this.x = x;
  2284. this.y = y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the Vector2 coordinates with the given floats
  2289. * @param x defines the first coordinate
  2290. * @param y defines the second coordinate
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.set = function (x, y) {
  2294. return this.copyFromFloats(x, y);
  2295. };
  2296. /**
  2297. * Add another vector with the current one
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2300. */
  2301. Vector2.prototype.add = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2306. * @param otherVector defines the other vector
  2307. * @param result defines the target vector
  2308. * @returns the unmodified current Vector2
  2309. */
  2310. Vector2.prototype.addToRef = function (otherVector, result) {
  2311. result.x = this.x + otherVector.x;
  2312. result.y = this.y + otherVector.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2317. * @param otherVector defines the other vector
  2318. * @returns the current updated Vector2
  2319. */
  2320. Vector2.prototype.addInPlace = function (otherVector) {
  2321. this.x += otherVector.x;
  2322. this.y += otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns a new Vector2
  2329. */
  2330. Vector2.prototype.addVector3 = function (otherVector) {
  2331. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2332. };
  2333. /**
  2334. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2335. * @param otherVector defines the other vector
  2336. * @returns a new Vector2
  2337. */
  2338. Vector2.prototype.subtract = function (otherVector) {
  2339. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2340. };
  2341. /**
  2342. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2343. * @param otherVector defines the other vector
  2344. * @param result defines the target vector
  2345. * @returns the unmodified current Vector2
  2346. */
  2347. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2348. result.x = this.x - otherVector.x;
  2349. result.y = this.y - otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2354. * @param otherVector defines the other vector
  2355. * @returns the current updated Vector2
  2356. */
  2357. Vector2.prototype.subtractInPlace = function (otherVector) {
  2358. this.x -= otherVector.x;
  2359. this.y -= otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Multiplies in place the current Vector2 coordinates by the given ones
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2368. this.x *= otherVector.x;
  2369. this.y *= otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.multiply = function (otherVector) {
  2378. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2379. };
  2380. /**
  2381. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2393. * @param x defines the first coordinate
  2394. * @param y defines the second coordinate
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiplyByFloats = function (x, y) {
  2398. return new Vector2(this.x * x, this.y * y);
  2399. };
  2400. /**
  2401. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @returns a new Vector2
  2404. */
  2405. Vector2.prototype.divide = function (otherVector) {
  2406. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2407. };
  2408. /**
  2409. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2410. * @param otherVector defines the other vector
  2411. * @param result defines the target vector
  2412. * @returns the unmodified current Vector2
  2413. */
  2414. Vector2.prototype.divideToRef = function (otherVector, result) {
  2415. result.x = this.x / otherVector.x;
  2416. result.y = this.y / otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Divides the current Vector3 coordinates by the given ones
  2421. * @param otherVector defines the other vector
  2422. * @returns the current updated Vector2
  2423. */
  2424. Vector2.prototype.divideInPlace = function (otherVector) {
  2425. return this.divideToRef(otherVector, this);
  2426. };
  2427. /**
  2428. * Gets a new Vector2 with current Vector2 negated coordinates
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.negate = function () {
  2432. return new Vector2(-this.x, -this.y);
  2433. };
  2434. /**
  2435. * Multiply the Vector2 coordinates by scale
  2436. * @param scale defines the scaling factor
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.scaleInPlace = function (scale) {
  2440. this.x *= scale;
  2441. this.y *= scale;
  2442. return this;
  2443. };
  2444. /**
  2445. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2446. * @param scale defines the scaling factor
  2447. * @returns a new Vector2
  2448. */
  2449. Vector2.prototype.scale = function (scale) {
  2450. var result = new Vector2(0, 0);
  2451. this.scaleToRef(scale, result);
  2452. return result;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleToRef = function (scale, result) {
  2461. result.x = this.x * scale;
  2462. result.y = this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2467. * @param scale defines the scale factor
  2468. * @param result defines the Vector2 object where to store the result
  2469. * @returns the unmodified current Vector2
  2470. */
  2471. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2472. result.x += this.x * scale;
  2473. result.y += this.y * scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Gets a boolean if two vectors are equals
  2478. * @param otherVector defines the other vector
  2479. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2480. */
  2481. Vector2.prototype.equals = function (otherVector) {
  2482. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2483. };
  2484. /**
  2485. * Gets a boolean if two vectors are equals (using an epsilon value)
  2486. * @param otherVector defines the other vector
  2487. * @param epsilon defines the minimal distance to consider equality
  2488. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2489. */
  2490. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2491. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2492. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2493. };
  2494. // Properties
  2495. /**
  2496. * Gets the length of the vector
  2497. * @returns the vector length (float)
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Gets the vector squared length
  2504. * @returns the vector squared length (float)
  2505. */
  2506. Vector2.prototype.lengthSquared = function () {
  2507. return (this.x * this.x + this.y * this.y);
  2508. };
  2509. // Methods
  2510. /**
  2511. * Normalize the vector
  2512. * @returns the current updated Vector2
  2513. */
  2514. Vector2.prototype.normalize = function () {
  2515. var len = this.length();
  2516. if (len === 0)
  2517. return this;
  2518. var num = 1.0 / len;
  2519. this.x *= num;
  2520. this.y *= num;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a new Vector2 copied from the Vector2
  2525. * @returns a new Vector2
  2526. */
  2527. Vector2.prototype.clone = function () {
  2528. return new Vector2(this.x, this.y);
  2529. };
  2530. // Statics
  2531. /**
  2532. * Gets a new Vector2(0, 0)
  2533. * @returns a new Vector2
  2534. */
  2535. Vector2.Zero = function () {
  2536. return new Vector2(0, 0);
  2537. };
  2538. /**
  2539. * Gets a new Vector2(1, 1)
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.One = function () {
  2543. return new Vector2(1, 1);
  2544. };
  2545. /**
  2546. * Gets a new Vector2 set from the given index element of the given array
  2547. * @param array defines the data source
  2548. * @param offset defines the offset in the data source
  2549. * @returns a new Vector2
  2550. */
  2551. Vector2.FromArray = function (array, offset) {
  2552. if (offset === void 0) { offset = 0; }
  2553. return new Vector2(array[offset], array[offset + 1]);
  2554. };
  2555. /**
  2556. * Sets "result" from the given index element of the given array
  2557. * @param array defines the data source
  2558. * @param offset defines the offset in the data source
  2559. * @param result defines the target vector
  2560. */
  2561. Vector2.FromArrayToRef = function (array, offset, result) {
  2562. result.x = array[offset];
  2563. result.y = array[offset + 1];
  2564. };
  2565. /**
  2566. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2567. * @param value1 defines 1st point of control
  2568. * @param value2 defines 2nd point of control
  2569. * @param value3 defines 3rd point of control
  2570. * @param value4 defines 4th point of control
  2571. * @param amount defines the interpolation factor
  2572. * @returns a new Vector2
  2573. */
  2574. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2575. var squared = amount * amount;
  2576. var cubed = amount * squared;
  2577. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2578. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2579. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2580. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2581. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2582. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * 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".
  2587. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2588. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2589. * @param value defines the value to clamp
  2590. * @param min defines the lower limit
  2591. * @param max defines the upper limit
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Clamp = function (value, min, max) {
  2595. var x = value.x;
  2596. x = (x > max.x) ? max.x : x;
  2597. x = (x < min.x) ? min.x : x;
  2598. var y = value.y;
  2599. y = (y > max.y) ? max.y : y;
  2600. y = (y < min.y) ? min.y : y;
  2601. return new Vector2(x, y);
  2602. };
  2603. /**
  2604. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2605. * @param value1 defines the 1st control point
  2606. * @param tangent1 defines the outgoing tangent
  2607. * @param value2 defines the 2nd control point
  2608. * @param tangent2 defines the incoming tangent
  2609. * @param amount defines the interpolation factor
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2613. var squared = amount * amount;
  2614. var cubed = amount * squared;
  2615. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2616. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2617. var part3 = (cubed - (2.0 * squared)) + amount;
  2618. var part4 = cubed - squared;
  2619. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2620. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2625. * @param start defines the start vector
  2626. * @param end defines the end vector
  2627. * @param amount defines the interpolation factor
  2628. * @returns a new Vector2
  2629. */
  2630. Vector2.Lerp = function (start, end, amount) {
  2631. var x = start.x + ((end.x - start.x) * amount);
  2632. var y = start.y + ((end.y - start.y) * amount);
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Gets the dot product of the vector "left" and the vector "right"
  2637. * @param left defines first vector
  2638. * @param right defines second vector
  2639. * @returns the dot product (float)
  2640. */
  2641. Vector2.Dot = function (left, right) {
  2642. return left.x * right.x + left.y * right.y;
  2643. };
  2644. /**
  2645. * Returns a new Vector2 equal to the normalized given vector
  2646. * @param vector defines the vector to normalize
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Normalize = function (vector) {
  2650. var newVector = vector.clone();
  2651. newVector.normalize();
  2652. return newVector;
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2656. * @param left defines 1st vector
  2657. * @param right defines 2nd vector
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.Minimize = function (left, right) {
  2661. var x = (left.x < right.x) ? left.x : right.x;
  2662. var y = (left.y < right.y) ? left.y : right.y;
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2667. * @param left defines 1st vector
  2668. * @param right defines 2nd vector
  2669. * @returns a new Vector2
  2670. */
  2671. Vector2.Maximize = function (left, right) {
  2672. var x = (left.x > right.x) ? left.x : right.x;
  2673. var y = (left.y > right.y) ? left.y : right.y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2678. * @param vector defines the vector to transform
  2679. * @param transformation defines the matrix to apply
  2680. * @returns a new Vector2
  2681. */
  2682. Vector2.Transform = function (vector, transformation) {
  2683. var r = Vector2.Zero();
  2684. Vector2.TransformToRef(vector, transformation, r);
  2685. return r;
  2686. };
  2687. /**
  2688. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2689. * @param vector defines the vector to transform
  2690. * @param transformation defines the matrix to apply
  2691. * @param result defines the target vector
  2692. */
  2693. Vector2.TransformToRef = function (vector, transformation, result) {
  2694. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2695. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2696. result.x = x;
  2697. result.y = y;
  2698. };
  2699. /**
  2700. * Determines if a given vector is included in a triangle
  2701. * @param p defines the vector to test
  2702. * @param p0 defines 1st triangle point
  2703. * @param p1 defines 2nd triangle point
  2704. * @param p2 defines 3rd triangle point
  2705. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2706. */
  2707. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2708. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2709. var sign = a < 0 ? -1 : 1;
  2710. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2711. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2712. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2713. };
  2714. /**
  2715. * Gets the distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the distance between vectors
  2719. */
  2720. Vector2.Distance = function (value1, value2) {
  2721. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2722. };
  2723. /**
  2724. * Returns the squared distance between the vectors "value1" and "value2"
  2725. * @param value1 defines first vector
  2726. * @param value2 defines second vector
  2727. * @returns the squared distance between vectors
  2728. */
  2729. Vector2.DistanceSquared = function (value1, value2) {
  2730. var x = value1.x - value2.x;
  2731. var y = value1.y - value2.y;
  2732. return (x * x) + (y * y);
  2733. };
  2734. /**
  2735. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2736. * @param value1 defines first vector
  2737. * @param value2 defines second vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Center = function (value1, value2) {
  2741. var center = value1.add(value2);
  2742. center.scaleInPlace(0.5);
  2743. return center;
  2744. };
  2745. /**
  2746. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2747. * @param p defines the middle point
  2748. * @param segA defines one point of the segment
  2749. * @param segB defines the other point of the segment
  2750. * @returns the shortest distance
  2751. */
  2752. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2753. var l2 = Vector2.DistanceSquared(segA, segB);
  2754. if (l2 === 0.0) {
  2755. return Vector2.Distance(p, segA);
  2756. }
  2757. var v = segB.subtract(segA);
  2758. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2759. var proj = segA.add(v.multiplyByFloats(t, t));
  2760. return Vector2.Distance(p, proj);
  2761. };
  2762. return Vector2;
  2763. }());
  2764. BABYLON.Vector2 = Vector2;
  2765. /**
  2766. * Classed used to store (x,y,z) vector representation
  2767. * A Vector3 is the main object used in 3D geometry
  2768. * It can represent etiher the coordinates of a point the space, either a direction
  2769. * Reminder: Babylon.js uses a left handed forward facing system
  2770. */
  2771. var Vector3 = /** @class */ (function () {
  2772. /**
  2773. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2774. * @param x defines the first coordinates (on X axis)
  2775. * @param y defines the second coordinates (on Y axis)
  2776. * @param z defines the third coordinates (on Z axis)
  2777. */
  2778. function Vector3(
  2779. /**
  2780. * Defines the first coordinates (on X axis)
  2781. */
  2782. x,
  2783. /**
  2784. * Defines the second coordinates (on Y axis)
  2785. */
  2786. y,
  2787. /**
  2788. * Defines the third coordinates (on Z axis)
  2789. */
  2790. z) {
  2791. if (x === void 0) { x = 0; }
  2792. if (y === void 0) { y = 0; }
  2793. if (z === void 0) { z = 0; }
  2794. this.x = x;
  2795. this.y = y;
  2796. this.z = z;
  2797. }
  2798. /**
  2799. * Creates a string representation of the Vector3
  2800. * @returns a string with the Vector3 coordinates.
  2801. */
  2802. Vector3.prototype.toString = function () {
  2803. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2804. };
  2805. /**
  2806. * Gets the class name
  2807. * @returns the string "Vector3"
  2808. */
  2809. Vector3.prototype.getClassName = function () {
  2810. return "Vector3";
  2811. };
  2812. /**
  2813. * Creates the Vector3 hash code
  2814. * @returns a number which tends to be unique between Vector3 instances
  2815. */
  2816. Vector3.prototype.getHashCode = function () {
  2817. var hash = this.x || 0;
  2818. hash = (hash * 397) ^ (this.y || 0);
  2819. hash = (hash * 397) ^ (this.z || 0);
  2820. return hash;
  2821. };
  2822. // Operators
  2823. /**
  2824. * Creates an array containing three elements : the coordinates of the Vector3
  2825. * @returns a new array of numbers
  2826. */
  2827. Vector3.prototype.asArray = function () {
  2828. var result = [];
  2829. this.toArray(result, 0);
  2830. return result;
  2831. };
  2832. /**
  2833. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2834. * @param array defines the destination array
  2835. * @param index defines the offset in the destination array
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.toArray = function (array, index) {
  2839. if (index === void 0) { index = 0; }
  2840. array[index] = this.x;
  2841. array[index + 1] = this.y;
  2842. array[index + 2] = this.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2847. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2848. */
  2849. Vector3.prototype.toQuaternion = function () {
  2850. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2851. };
  2852. /**
  2853. * Adds the given vector to the current Vector3
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.addInPlace = function (otherVector) {
  2858. this.x += otherVector.x;
  2859. this.y += otherVector.y;
  2860. this.z += otherVector.z;
  2861. return this;
  2862. };
  2863. /**
  2864. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2865. * @param otherVector defines the second operand
  2866. * @returns the resulting Vector3
  2867. */
  2868. Vector3.prototype.add = function (otherVector) {
  2869. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2870. };
  2871. /**
  2872. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2873. * @param otherVector defines the second operand
  2874. * @param result defines the Vector3 object where to store the result
  2875. * @returns the current Vector3
  2876. */
  2877. Vector3.prototype.addToRef = function (otherVector, result) {
  2878. result.x = this.x + otherVector.x;
  2879. result.y = this.y + otherVector.y;
  2880. result.z = this.z + otherVector.z;
  2881. return this;
  2882. };
  2883. /**
  2884. * Subtract the given vector from the current Vector3
  2885. * @param otherVector defines the second operand
  2886. * @returns the current updated Vector3
  2887. */
  2888. Vector3.prototype.subtractInPlace = function (otherVector) {
  2889. this.x -= otherVector.x;
  2890. this.y -= otherVector.y;
  2891. this.z -= otherVector.z;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2896. * @param otherVector defines the second operand
  2897. * @returns the resulting Vector3
  2898. */
  2899. Vector3.prototype.subtract = function (otherVector) {
  2900. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2901. };
  2902. /**
  2903. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2904. * @param otherVector defines the second operand
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2909. result.x = this.x - otherVector.x;
  2910. result.y = this.y - otherVector.y;
  2911. result.z = this.z - otherVector.z;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2916. * @param x defines the x coordinate of the operand
  2917. * @param y defines the y coordinate of the operand
  2918. * @param z defines the z coordinate of the operand
  2919. * @returns the resulting Vector3
  2920. */
  2921. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2922. return new Vector3(this.x - x, this.y - y, this.z - z);
  2923. };
  2924. /**
  2925. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2926. * @param x defines the x coordinate of the operand
  2927. * @param y defines the y coordinate of the operand
  2928. * @param z defines the z coordinate of the operand
  2929. * @param result defines the Vector3 object where to store the result
  2930. * @returns the current Vector3
  2931. */
  2932. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2933. result.x = this.x - x;
  2934. result.y = this.y - y;
  2935. result.z = this.z - z;
  2936. return this;
  2937. };
  2938. /**
  2939. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2940. * @returns a new Vector3
  2941. */
  2942. Vector3.prototype.negate = function () {
  2943. return new Vector3(-this.x, -this.y, -this.z);
  2944. };
  2945. /**
  2946. * Multiplies the Vector3 coordinates by the float "scale"
  2947. * @param scale defines the multiplier factor
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.scaleInPlace = function (scale) {
  2951. this.x *= scale;
  2952. this.y *= scale;
  2953. this.z *= scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2958. * @param scale defines the multiplier factor
  2959. * @returns a new Vector3
  2960. */
  2961. Vector3.prototype.scale = function (scale) {
  2962. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2963. };
  2964. /**
  2965. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2966. * @param scale defines the multiplier factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the current Vector3
  2969. */
  2970. Vector3.prototype.scaleToRef = function (scale, result) {
  2971. result.x = this.x * scale;
  2972. result.y = this.y * scale;
  2973. result.z = this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2978. * @param scale defines the scale factor
  2979. * @param result defines the Vector3 object where to store the result
  2980. * @returns the unmodified current Vector3
  2981. */
  2982. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2983. result.x += this.x * scale;
  2984. result.y += this.y * scale;
  2985. result.z += this.z * scale;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2990. * @param otherVector defines the second operand
  2991. * @returns true if both vectors are equals
  2992. */
  2993. Vector3.prototype.equals = function (otherVector) {
  2994. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2995. };
  2996. /**
  2997. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2998. * @param otherVector defines the second operand
  2999. * @param epsilon defines the minimal distance to define values as equals
  3000. * @returns true if both vectors are distant less than epsilon
  3001. */
  3002. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3003. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3004. 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);
  3005. };
  3006. /**
  3007. * Returns true if the current Vector3 coordinates equals the given floats
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @returns true if both vectors are equals
  3012. */
  3013. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3014. return this.x === x && this.y === y && this.z === z;
  3015. };
  3016. /**
  3017. * Multiplies the current Vector3 coordinates by the given ones
  3018. * @param otherVector defines the second operand
  3019. * @returns the current updated Vector3
  3020. */
  3021. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3022. this.x *= otherVector.x;
  3023. this.y *= otherVector.y;
  3024. this.z *= otherVector.z;
  3025. return this;
  3026. };
  3027. /**
  3028. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3029. * @param otherVector defines the second operand
  3030. * @returns the new Vector3
  3031. */
  3032. Vector3.prototype.multiply = function (otherVector) {
  3033. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3034. };
  3035. /**
  3036. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3037. * @param otherVector defines the second operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3042. result.x = this.x * otherVector.x;
  3043. result.y = this.y * otherVector.y;
  3044. result.z = this.z * otherVector.z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3049. * @param x defines the x coordinate of the operand
  3050. * @param y defines the y coordinate of the operand
  3051. * @param z defines the z coordinate of the operand
  3052. * @returns the new Vector3
  3053. */
  3054. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3055. return new Vector3(this.x * x, this.y * y, this.z * z);
  3056. };
  3057. /**
  3058. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3059. * @param otherVector defines the second operand
  3060. * @returns the new Vector3
  3061. */
  3062. Vector3.prototype.divide = function (otherVector) {
  3063. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3067. * @param otherVector defines the second operand
  3068. * @param result defines the Vector3 object where to store the result
  3069. * @returns the current Vector3
  3070. */
  3071. Vector3.prototype.divideToRef = function (otherVector, result) {
  3072. result.x = this.x / otherVector.x;
  3073. result.y = this.y / otherVector.y;
  3074. result.z = this.z / otherVector.z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Divides the current Vector3 coordinates by the given ones.
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.divideInPlace = function (otherVector) {
  3083. return this.divideToRef(otherVector, this);
  3084. };
  3085. /**
  3086. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3087. * @param other defines the second operand
  3088. * @returns the current updated Vector3
  3089. */
  3090. Vector3.prototype.minimizeInPlace = function (other) {
  3091. if (other.x < this.x)
  3092. this.x = other.x;
  3093. if (other.y < this.y)
  3094. this.y = other.y;
  3095. if (other.z < this.z)
  3096. this.z = other.z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3101. * @param other defines the second operand
  3102. * @returns the current updated Vector3
  3103. */
  3104. Vector3.prototype.maximizeInPlace = function (other) {
  3105. if (other.x > this.x)
  3106. this.x = other.x;
  3107. if (other.y > this.y)
  3108. this.y = other.y;
  3109. if (other.z > this.z)
  3110. this.z = other.z;
  3111. return this;
  3112. };
  3113. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3114. /**
  3115. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3116. */
  3117. get: function () {
  3118. var absX = Math.abs(this.x);
  3119. var absY = Math.abs(this.y);
  3120. if (absX !== absY) {
  3121. return true;
  3122. }
  3123. var absZ = Math.abs(this.z);
  3124. if (absX !== absZ) {
  3125. return true;
  3126. }
  3127. if (absY !== absZ) {
  3128. return true;
  3129. }
  3130. return false;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. // Properties
  3136. /**
  3137. * Gets the length of the Vector3
  3138. * @returns the length of the Vecto3
  3139. */
  3140. Vector3.prototype.length = function () {
  3141. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3142. };
  3143. /**
  3144. * Gets the squared length of the Vector3
  3145. * @returns squared length of the Vector3
  3146. */
  3147. Vector3.prototype.lengthSquared = function () {
  3148. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3149. };
  3150. /**
  3151. * Normalize the current Vector3.
  3152. * Please note that this is an in place operation.
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.normalize = function () {
  3156. var len = this.length();
  3157. if (len === 0 || len === 1.0)
  3158. return this;
  3159. var num = 1.0 / len;
  3160. this.x *= num;
  3161. this.y *= num;
  3162. this.z *= num;
  3163. return this;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to a new vector
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.prototype.normalizeToNew = function () {
  3170. var normalized = new Vector3(0, 0, 0);
  3171. this.normalizeToRef(normalized);
  3172. return normalized;
  3173. };
  3174. /**
  3175. * Normalize the current Vector3 to the reference
  3176. * @param reference define the Vector3 to update
  3177. * @returns the updated Vector3
  3178. */
  3179. Vector3.prototype.normalizeToRef = function (reference) {
  3180. var len = this.length();
  3181. if (len === 0 || len === 1.0) {
  3182. reference.set(this.x, this.y, this.z);
  3183. return reference;
  3184. }
  3185. var scale = 1.0 / len;
  3186. this.scaleToRef(scale, reference);
  3187. return reference;
  3188. };
  3189. /**
  3190. * Creates a new Vector3 copied from the current Vector3
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.prototype.clone = function () {
  3194. return new Vector3(this.x, this.y, this.z);
  3195. };
  3196. /**
  3197. * Copies the given vector coordinates to the current Vector3 ones
  3198. * @param source defines the source Vector3
  3199. * @returns the current updated Vector3
  3200. */
  3201. Vector3.prototype.copyFrom = function (source) {
  3202. this.x = source.x;
  3203. this.y = source.y;
  3204. this.z = source.z;
  3205. return this;
  3206. };
  3207. /**
  3208. * Copies the given floats to the current Vector3 coordinates
  3209. * @param x defines the x coordinate of the operand
  3210. * @param y defines the y coordinate of the operand
  3211. * @param z defines the z coordinate of the operand
  3212. * @returns the current updated Vector3
  3213. */
  3214. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3215. this.x = x;
  3216. this.y = y;
  3217. this.z = z;
  3218. return this;
  3219. };
  3220. /**
  3221. * Copies the given floats to the current Vector3 coordinates
  3222. * @param x defines the x coordinate of the operand
  3223. * @param y defines the y coordinate of the operand
  3224. * @param z defines the z coordinate of the operand
  3225. * @returns the current updated Vector3
  3226. */
  3227. Vector3.prototype.set = function (x, y, z) {
  3228. return this.copyFromFloats(x, y, z);
  3229. };
  3230. // Statics
  3231. /**
  3232. * Get the clip factor between two vectors
  3233. * @param vector0 defines the first operand
  3234. * @param vector1 defines the second operand
  3235. * @param axis defines the axis to use
  3236. * @param size defines the size along the axis
  3237. * @returns the clip factor
  3238. */
  3239. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3240. var d0 = Vector3.Dot(vector0, axis) - size;
  3241. var d1 = Vector3.Dot(vector1, axis) - size;
  3242. var s = d0 / (d0 - d1);
  3243. return s;
  3244. };
  3245. /**
  3246. * Get angle between two vectors
  3247. * @param vector0 angle between vector0 and vector1
  3248. * @param vector1 angle between vector0 and vector1
  3249. * @param normal direction of the normal
  3250. * @return the angle between vector0 and vector1
  3251. */
  3252. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3253. var v0 = vector0.clone().normalize();
  3254. var v1 = vector1.clone().normalize();
  3255. var dot = Vector3.Dot(v0, v1);
  3256. var n = Vector3.Cross(v0, v1);
  3257. if (Vector3.Dot(n, normal) > 0) {
  3258. return Math.acos(dot);
  3259. }
  3260. return -Math.acos(dot);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given array
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.FromArray = function (array, offset) {
  3269. if (!offset) {
  3270. offset = 0;
  3271. }
  3272. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3276. * This function is deprecated. Use FromArray instead
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.FromFloatArray = function (array, offset) {
  3282. return Vector3.FromArray(array, offset);
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromArrayToRef = function (array, offset, result) {
  3291. result.x = array[offset];
  3292. result.y = array[offset + 1];
  3293. result.z = array[offset + 2];
  3294. };
  3295. /**
  3296. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3297. * This function is deprecated. Use FromArrayToRef instead.
  3298. * @param array defines the source array
  3299. * @param offset defines the offset in the source array
  3300. * @param result defines the Vector3 where to store the result
  3301. */
  3302. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3303. return Vector3.FromArrayToRef(array, offset, result);
  3304. };
  3305. /**
  3306. * Sets the given vector "result" with the given floats.
  3307. * @param x defines the x coordinate of the source
  3308. * @param y defines the y coordinate of the source
  3309. * @param z defines the z coordinate of the source
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3313. result.x = x;
  3314. result.y = y;
  3315. result.z = z;
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3319. * @returns a new empty Vector3
  3320. */
  3321. Vector3.Zero = function () {
  3322. return new Vector3(0.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3326. * @returns a new unit Vector3
  3327. */
  3328. Vector3.One = function () {
  3329. return new Vector3(1.0, 1.0, 1.0);
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3333. * @returns a new up Vector3
  3334. */
  3335. Vector3.Up = function () {
  3336. return new Vector3(0.0, 1.0, 0.0);
  3337. };
  3338. /**
  3339. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3340. * @returns a new down Vector3
  3341. */
  3342. Vector3.Down = function () {
  3343. return new Vector3(0.0, -1.0, 0.0);
  3344. };
  3345. /**
  3346. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3347. * @returns a new forward Vector3
  3348. */
  3349. Vector3.Forward = function () {
  3350. return new Vector3(0.0, 0.0, 1.0);
  3351. };
  3352. /**
  3353. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3354. * @returns a new right Vector3
  3355. */
  3356. Vector3.Right = function () {
  3357. return new Vector3(1.0, 0.0, 0.0);
  3358. };
  3359. /**
  3360. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3361. * @returns a new left Vector3
  3362. */
  3363. Vector3.Left = function () {
  3364. return new Vector3(-1.0, 0.0, 0.0);
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the transformed Vector3
  3372. */
  3373. Vector3.TransformCoordinates = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3380. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3389. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3390. result.x = x / w;
  3391. result.y = y / w;
  3392. result.z = z / w;
  3393. };
  3394. /**
  3395. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3396. * This method computes tranformed coordinates only, not transformed direction vectors
  3397. * @param x define the x coordinate of the source vector
  3398. * @param y define the y coordinate of the source vector
  3399. * @param z define the z coordinate of the source vector
  3400. * @param transformation defines the transformation matrix
  3401. * @param result defines the Vector3 where to store the result
  3402. */
  3403. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3404. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3405. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3406. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3407. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3408. result.x = rx / rw;
  3409. result.y = ry / rw;
  3410. result.z = rz / rw;
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.TransformNormal = function (vector, transformation) {
  3420. var result = Vector3.Zero();
  3421. Vector3.TransformNormalToRef(vector, transformation, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3426. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3427. * @param vector defines the Vector3 to transform
  3428. * @param transformation defines the transformation matrix
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3432. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3433. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3434. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3435. result.x = x;
  3436. result.y = y;
  3437. result.z = z;
  3438. };
  3439. /**
  3440. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param x define the x coordinate of the source vector
  3443. * @param y define the y coordinate of the source vector
  3444. * @param z define the z coordinate of the source vector
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3449. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3450. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3451. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3455. * @param value1 defines the first control point
  3456. * @param value2 defines the second control point
  3457. * @param value3 defines the third control point
  3458. * @param value4 defines the fourth control point
  3459. * @param amount defines the amount on the spline to use
  3460. * @returns the new Vector3
  3461. */
  3462. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3463. var squared = amount * amount;
  3464. var cubed = amount * squared;
  3465. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3466. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3467. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3468. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3469. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3470. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3471. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3472. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3473. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * 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"
  3478. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3479. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3480. * @param value defines the current value
  3481. * @param min defines the lower range value
  3482. * @param max defines the upper range value
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.Clamp = function (value, min, max) {
  3486. var x = value.x;
  3487. x = (x > max.x) ? max.x : x;
  3488. x = (x < min.x) ? min.x : x;
  3489. var y = value.y;
  3490. y = (y > max.y) ? max.y : y;
  3491. y = (y < min.y) ? min.y : y;
  3492. var z = value.z;
  3493. z = (z > max.z) ? max.z : z;
  3494. z = (z < min.z) ? min.z : z;
  3495. return new Vector3(x, y, z);
  3496. };
  3497. /**
  3498. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3499. * @param value1 defines the first control point
  3500. * @param tangent1 defines the first tangent vector
  3501. * @param value2 defines the second control point
  3502. * @param tangent2 defines the second tangent vector
  3503. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3507. var squared = amount * amount;
  3508. var cubed = amount * squared;
  3509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3511. var part3 = (cubed - (2.0 * squared)) + amount;
  3512. var part4 = cubed - squared;
  3513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3516. return new Vector3(x, y, z);
  3517. };
  3518. /**
  3519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.Lerp = function (start, end, amount) {
  3526. var result = new Vector3(0, 0, 0);
  3527. Vector3.LerpToRef(start, end, amount, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3532. * @param start defines the start value
  3533. * @param end defines the end value
  3534. * @param amount max defines amount between both (between 0 and 1)
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.LerpToRef = function (start, end, amount, result) {
  3538. result.x = start.x + ((end.x - start.x) * amount);
  3539. result.y = start.y + ((end.y - start.y) * amount);
  3540. result.z = start.z + ((end.z - start.z) * amount);
  3541. };
  3542. /**
  3543. * Returns the dot product (float) between the vectors "left" and "right"
  3544. * @param left defines the left operand
  3545. * @param right defines the right operand
  3546. * @returns the dot product
  3547. */
  3548. Vector3.Dot = function (left, right) {
  3549. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @returns the cross product
  3557. */
  3558. Vector3.Cross = function (left, right) {
  3559. var result = Vector3.Zero();
  3560. Vector3.CrossToRef(left, right, result);
  3561. return result;
  3562. };
  3563. /**
  3564. * Sets the given vector "result" with the cross product of "left" and "right"
  3565. * The cross product is then orthogonal to both "left" and "right"
  3566. * @param left defines the left operand
  3567. * @param right defines the right operand
  3568. * @param result defines the Vector3 where to store the result
  3569. */
  3570. Vector3.CrossToRef = function (left, right, result) {
  3571. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3572. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3573. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3574. result.copyFrom(MathTmp.Vector3[0]);
  3575. };
  3576. /**
  3577. * Returns a new Vector3 as the normalization of the given vector
  3578. * @param vector defines the Vector3 to normalize
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Normalize = function (vector) {
  3582. var result = Vector3.Zero();
  3583. Vector3.NormalizeToRef(vector, result);
  3584. return result;
  3585. };
  3586. /**
  3587. * Sets the given vector "result" with the normalization of the given first vector
  3588. * @param vector defines the Vector3 to normalize
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.NormalizeToRef = function (vector, result) {
  3592. result.copyFrom(vector);
  3593. result.normalize();
  3594. };
  3595. /**
  3596. * Project a Vector3 onto screen space
  3597. * @param vector defines the Vector3 to project
  3598. * @param world defines the world matrix to use
  3599. * @param transform defines the transform (view x projection) matrix to use
  3600. * @param viewport defines the screen viewport to use
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Project = function (vector, world, transform, viewport) {
  3604. var cw = viewport.width;
  3605. var ch = viewport.height;
  3606. var cx = viewport.x;
  3607. var cy = viewport.y;
  3608. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3609. 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);
  3610. var matrix = MathTmp.Matrix[0];
  3611. world.multiplyToRef(transform, matrix);
  3612. matrix.multiplyToRef(viewportMatrix, matrix);
  3613. return Vector3.TransformCoordinates(vector, matrix);
  3614. };
  3615. /**
  3616. * Unproject from screen space to object space
  3617. * @param source defines the screen space Vector3 to use
  3618. * @param viewportWidth defines the current width of the viewport
  3619. * @param viewportHeight defines the current height of the viewport
  3620. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3621. * @param transform defines the transform (view x projection) matrix to use
  3622. * @returns the new Vector3
  3623. */
  3624. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3625. var matrix = MathTmp.Matrix[0];
  3626. world.multiplyToRef(transform, matrix);
  3627. matrix.invert();
  3628. source.x = source.x / viewportWidth * 2 - 1;
  3629. source.y = -(source.y / viewportHeight * 2 - 1);
  3630. var vector = Vector3.TransformCoordinates(source, matrix);
  3631. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3632. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3633. vector = vector.scale(1.0 / num);
  3634. }
  3635. return vector;
  3636. };
  3637. /**
  3638. * Unproject from screen space to object space
  3639. * @param source defines the screen space Vector3 to use
  3640. * @param viewportWidth defines the current width of the viewport
  3641. * @param viewportHeight defines the current height of the viewport
  3642. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3643. * @param view defines the view matrix to use
  3644. * @param projection defines the projection matrix to use
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3648. var result = Vector3.Zero();
  3649. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Unproject from screen space to object space
  3654. * @param source defines the screen space Vector3 to use
  3655. * @param viewportWidth defines the current width of the viewport
  3656. * @param viewportHeight defines the current height of the viewport
  3657. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3658. * @param view defines the view matrix to use
  3659. * @param projection defines the projection matrix to use
  3660. * @param result defines the Vector3 where to store the result
  3661. */
  3662. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3663. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3664. };
  3665. /**
  3666. * Unproject from screen space to object space
  3667. * @param sourceX defines the screen space x coordinate to use
  3668. * @param sourceY defines the screen space y coordinate to use
  3669. * @param sourceZ defines the screen space z coordinate to use
  3670. * @param viewportWidth defines the current width of the viewport
  3671. * @param viewportHeight defines the current height of the viewport
  3672. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3673. * @param view defines the view matrix to use
  3674. * @param projection defines the projection matrix to use
  3675. * @param result defines the Vector3 where to store the result
  3676. */
  3677. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3678. var matrix = MathTmp.Matrix[0];
  3679. world.multiplyToRef(view, matrix);
  3680. matrix.multiplyToRef(projection, matrix);
  3681. matrix.invert();
  3682. var screenSource = MathTmp.Vector3[0];
  3683. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3684. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3685. screenSource.z = 2 * sourceZ - 1.0;
  3686. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3687. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3688. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3689. result.scaleInPlace(1.0 / num);
  3690. }
  3691. };
  3692. /**
  3693. * Gets the minimal coordinate values between two Vector3
  3694. * @param left defines the first operand
  3695. * @param right defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Minimize = function (left, right) {
  3699. var min = left.clone();
  3700. min.minimizeInPlace(right);
  3701. return min;
  3702. };
  3703. /**
  3704. * Gets the maximal coordinate values between two Vector3
  3705. * @param left defines the first operand
  3706. * @param right defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Maximize = function (left, right) {
  3710. var max = left.clone();
  3711. max.maximizeInPlace(right);
  3712. return max;
  3713. };
  3714. /**
  3715. * Returns the distance between the vectors "value1" and "value2"
  3716. * @param value1 defines the first operand
  3717. * @param value2 defines the second operand
  3718. * @returns the distance
  3719. */
  3720. Vector3.Distance = function (value1, value2) {
  3721. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3722. };
  3723. /**
  3724. * Returns the squared distance between the vectors "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the squared distance
  3728. */
  3729. Vector3.DistanceSquared = function (value1, value2) {
  3730. var x = value1.x - value2.x;
  3731. var y = value1.y - value2.y;
  3732. var z = value1.z - value2.z;
  3733. return (x * x) + (y * y) + (z * z);
  3734. };
  3735. /**
  3736. * Returns a new Vector3 located at the center between "value1" and "value2"
  3737. * @param value1 defines the first operand
  3738. * @param value2 defines the second operand
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.Center = function (value1, value2) {
  3742. var center = value1.add(value2);
  3743. center.scaleInPlace(0.5);
  3744. return center;
  3745. };
  3746. /**
  3747. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3748. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3749. * to something in order to rotate it from its local system to the given target system
  3750. * Note: axis1, axis2 and axis3 are normalized during this operation
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @returns a new Vector3
  3755. */
  3756. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3757. var rotation = Vector3.Zero();
  3758. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3759. return rotation;
  3760. };
  3761. /**
  3762. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3763. * @param axis1 defines the first axis
  3764. * @param axis2 defines the second axis
  3765. * @param axis3 defines the third axis
  3766. * @param ref defines the Vector3 where to store the result
  3767. */
  3768. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3769. var quat = MathTmp.Quaternion[0];
  3770. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3771. quat.toEulerAnglesToRef(ref);
  3772. };
  3773. return Vector3;
  3774. }());
  3775. BABYLON.Vector3 = Vector3;
  3776. //Vector4 class created for EulerAngle class conversion to Quaternion
  3777. var Vector4 = /** @class */ (function () {
  3778. /**
  3779. * Creates a Vector4 object from the given floats.
  3780. */
  3781. function Vector4(x, y, z, w) {
  3782. this.x = x;
  3783. this.y = y;
  3784. this.z = z;
  3785. this.w = w;
  3786. }
  3787. /**
  3788. * Returns the string with the Vector4 coordinates.
  3789. */
  3790. Vector4.prototype.toString = function () {
  3791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3792. };
  3793. /**
  3794. * Returns the string "Vector4".
  3795. */
  3796. Vector4.prototype.getClassName = function () {
  3797. return "Vector4";
  3798. };
  3799. /**
  3800. * Returns the Vector4 hash code.
  3801. */
  3802. Vector4.prototype.getHashCode = function () {
  3803. var hash = this.x || 0;
  3804. hash = (hash * 397) ^ (this.y || 0);
  3805. hash = (hash * 397) ^ (this.z || 0);
  3806. hash = (hash * 397) ^ (this.w || 0);
  3807. return hash;
  3808. };
  3809. // Operators
  3810. /**
  3811. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3812. */
  3813. Vector4.prototype.asArray = function () {
  3814. var result = new Array();
  3815. this.toArray(result, 0);
  3816. return result;
  3817. };
  3818. /**
  3819. * Populates the given array from the given index with the Vector4 coordinates.
  3820. * Returns the Vector4.
  3821. */
  3822. Vector4.prototype.toArray = function (array, index) {
  3823. if (index === undefined) {
  3824. index = 0;
  3825. }
  3826. array[index] = this.x;
  3827. array[index + 1] = this.y;
  3828. array[index + 2] = this.z;
  3829. array[index + 3] = this.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Adds the given vector to the current Vector4.
  3834. * Returns the updated Vector4.
  3835. */
  3836. Vector4.prototype.addInPlace = function (otherVector) {
  3837. this.x += otherVector.x;
  3838. this.y += otherVector.y;
  3839. this.z += otherVector.z;
  3840. this.w += otherVector.w;
  3841. return this;
  3842. };
  3843. /**
  3844. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3845. */
  3846. Vector4.prototype.add = function (otherVector) {
  3847. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3848. };
  3849. /**
  3850. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3851. * Returns the current Vector4.
  3852. */
  3853. Vector4.prototype.addToRef = function (otherVector, result) {
  3854. result.x = this.x + otherVector.x;
  3855. result.y = this.y + otherVector.y;
  3856. result.z = this.z + otherVector.z;
  3857. result.w = this.w + otherVector.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Subtract in place the given vector from the current Vector4.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.subtractInPlace = function (otherVector) {
  3865. this.x -= otherVector.x;
  3866. this.y -= otherVector.y;
  3867. this.z -= otherVector.z;
  3868. this.w -= otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3873. */
  3874. Vector4.prototype.subtract = function (otherVector) {
  3875. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3876. };
  3877. /**
  3878. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3879. * Returns the current Vector4.
  3880. */
  3881. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3882. result.x = this.x - otherVector.x;
  3883. result.y = this.y - otherVector.y;
  3884. result.z = this.z - otherVector.z;
  3885. result.w = this.w - otherVector.w;
  3886. return this;
  3887. };
  3888. /**
  3889. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3892. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3893. };
  3894. /**
  3895. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3896. * Returns the current Vector4.
  3897. */
  3898. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3899. result.x = this.x - x;
  3900. result.y = this.y - y;
  3901. result.z = this.z - z;
  3902. result.w = this.w - w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3907. */
  3908. Vector4.prototype.negate = function () {
  3909. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3910. };
  3911. /**
  3912. * Multiplies the current Vector4 coordinates by scale (float).
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.scaleInPlace = function (scale) {
  3916. this.x *= scale;
  3917. this.y *= scale;
  3918. this.z *= scale;
  3919. this.w *= scale;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3924. */
  3925. Vector4.prototype.scale = function (scale) {
  3926. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.scaleToRef = function (scale, result) {
  3933. result.x = this.x * scale;
  3934. result.y = this.y * scale;
  3935. result.z = this.z * scale;
  3936. result.w = this.w * scale;
  3937. return this;
  3938. };
  3939. /**
  3940. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3941. * @param scale defines the scale factor
  3942. * @param result defines the Vector4 object where to store the result
  3943. * @returns the unmodified current Vector4
  3944. */
  3945. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3946. result.x += this.x * scale;
  3947. result.y += this.y * scale;
  3948. result.z += this.z * scale;
  3949. result.w += this.w * scale;
  3950. return this;
  3951. };
  3952. /**
  3953. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3954. */
  3955. Vector4.prototype.equals = function (otherVector) {
  3956. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3957. };
  3958. /**
  3959. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3960. */
  3961. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3962. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3963. return otherVector
  3964. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3967. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3968. };
  3969. /**
  3970. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3971. */
  3972. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3973. return this.x === x && this.y === y && this.z === z && this.w === w;
  3974. };
  3975. /**
  3976. * Multiplies in place the current Vector4 by the given one.
  3977. * Returns the updated Vector4.
  3978. */
  3979. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3980. this.x *= otherVector.x;
  3981. this.y *= otherVector.y;
  3982. this.z *= otherVector.z;
  3983. this.w *= otherVector.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3988. */
  3989. Vector4.prototype.multiply = function (otherVector) {
  3990. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3991. };
  3992. /**
  3993. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3994. * Returns the current Vector4.
  3995. */
  3996. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3997. result.x = this.x * otherVector.x;
  3998. result.y = this.y * otherVector.y;
  3999. result.z = this.z * otherVector.z;
  4000. result.w = this.w * otherVector.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4005. */
  4006. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4007. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4008. };
  4009. /**
  4010. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4011. */
  4012. Vector4.prototype.divide = function (otherVector) {
  4013. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4014. };
  4015. /**
  4016. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4017. * Returns the current Vector4.
  4018. */
  4019. Vector4.prototype.divideToRef = function (otherVector, result) {
  4020. result.x = this.x / otherVector.x;
  4021. result.y = this.y / otherVector.y;
  4022. result.z = this.z / otherVector.z;
  4023. result.w = this.w / otherVector.w;
  4024. return this;
  4025. };
  4026. /**
  4027. * Divides the current Vector3 coordinates by the given ones.
  4028. * @returns the updated Vector3.
  4029. */
  4030. Vector4.prototype.divideInPlace = function (otherVector) {
  4031. return this.divideToRef(otherVector, this);
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.minimizeInPlace = function (other) {
  4039. if (other.x < this.x)
  4040. this.x = other.x;
  4041. if (other.y < this.y)
  4042. this.y = other.y;
  4043. if (other.z < this.z)
  4044. this.z = other.z;
  4045. if (other.w < this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4051. * @param other defines the second operand
  4052. * @returns the current updated Vector4
  4053. */
  4054. Vector4.prototype.maximizeInPlace = function (other) {
  4055. if (other.x > this.x)
  4056. this.x = other.x;
  4057. if (other.y > this.y)
  4058. this.y = other.y;
  4059. if (other.z > this.z)
  4060. this.z = other.z;
  4061. if (other.w > this.w)
  4062. this.w = other.w;
  4063. return this;
  4064. };
  4065. // Properties
  4066. /**
  4067. * Returns the Vector4 length (float).
  4068. */
  4069. Vector4.prototype.length = function () {
  4070. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4071. };
  4072. /**
  4073. * Returns the Vector4 squared length (float).
  4074. */
  4075. Vector4.prototype.lengthSquared = function () {
  4076. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4077. };
  4078. // Methods
  4079. /**
  4080. * Normalizes in place the Vector4.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.normalize = function () {
  4084. var len = this.length();
  4085. if (len === 0)
  4086. return this;
  4087. var num = 1.0 / len;
  4088. this.x *= num;
  4089. this.y *= num;
  4090. this.z *= num;
  4091. this.w *= num;
  4092. return this;
  4093. };
  4094. /**
  4095. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4096. */
  4097. Vector4.prototype.toVector3 = function () {
  4098. return new Vector3(this.x, this.y, this.z);
  4099. };
  4100. /**
  4101. * Returns a new Vector4 copied from the current one.
  4102. */
  4103. Vector4.prototype.clone = function () {
  4104. return new Vector4(this.x, this.y, this.z, this.w);
  4105. };
  4106. /**
  4107. * Updates the current Vector4 with the given one coordinates.
  4108. * Returns the updated Vector4.
  4109. */
  4110. Vector4.prototype.copyFrom = function (source) {
  4111. this.x = source.x;
  4112. this.y = source.y;
  4113. this.z = source.z;
  4114. this.w = source.w;
  4115. return this;
  4116. };
  4117. /**
  4118. * Updates the current Vector4 coordinates with the given floats.
  4119. * Returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4122. this.x = x;
  4123. this.y = y;
  4124. this.z = z;
  4125. this.w = w;
  4126. return this;
  4127. };
  4128. /**
  4129. * Updates the current Vector4 coordinates with the given floats.
  4130. * Returns the updated Vector4.
  4131. */
  4132. Vector4.prototype.set = function (x, y, z, w) {
  4133. return this.copyFromFloats(x, y, z, w);
  4134. };
  4135. // Statics
  4136. /**
  4137. * Returns a new Vector4 set from the starting index of the given array.
  4138. */
  4139. Vector4.FromArray = function (array, offset) {
  4140. if (!offset) {
  4141. offset = 0;
  4142. }
  4143. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" from the starting index of the given array.
  4147. */
  4148. Vector4.FromArrayToRef = function (array, offset, result) {
  4149. result.x = array[offset];
  4150. result.y = array[offset + 1];
  4151. result.z = array[offset + 2];
  4152. result.w = array[offset + 3];
  4153. };
  4154. /**
  4155. * Updates the given vector "result" from the starting index of the given Float32Array.
  4156. */
  4157. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4158. Vector4.FromArrayToRef(array, offset, result);
  4159. };
  4160. /**
  4161. * Updates the given vector "result" coordinates from the given floats.
  4162. */
  4163. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4164. result.x = x;
  4165. result.y = y;
  4166. result.z = z;
  4167. result.w = w;
  4168. };
  4169. /**
  4170. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4171. */
  4172. Vector4.Zero = function () {
  4173. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4177. */
  4178. Vector4.One = function () {
  4179. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4180. };
  4181. /**
  4182. * Returns a new normalized Vector4 from the given one.
  4183. */
  4184. Vector4.Normalize = function (vector) {
  4185. var result = Vector4.Zero();
  4186. Vector4.NormalizeToRef(vector, result);
  4187. return result;
  4188. };
  4189. /**
  4190. * Updates the given vector "result" from the normalization of the given one.
  4191. */
  4192. Vector4.NormalizeToRef = function (vector, result) {
  4193. result.copyFrom(vector);
  4194. result.normalize();
  4195. };
  4196. Vector4.Minimize = function (left, right) {
  4197. var min = left.clone();
  4198. min.minimizeInPlace(right);
  4199. return min;
  4200. };
  4201. Vector4.Maximize = function (left, right) {
  4202. var max = left.clone();
  4203. max.maximizeInPlace(right);
  4204. return max;
  4205. };
  4206. /**
  4207. * Returns the distance (float) between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Distance = function (value1, value2) {
  4210. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4211. };
  4212. /**
  4213. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4214. */
  4215. Vector4.DistanceSquared = function (value1, value2) {
  4216. var x = value1.x - value2.x;
  4217. var y = value1.y - value2.y;
  4218. var z = value1.z - value2.z;
  4219. var w = value1.w - value2.w;
  4220. return (x * x) + (y * y) + (z * z) + (w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4224. */
  4225. Vector4.Center = function (value1, value2) {
  4226. var center = value1.add(value2);
  4227. center.scaleInPlace(0.5);
  4228. return center;
  4229. };
  4230. /**
  4231. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4232. * This methods computes transformed normalized direction vectors only.
  4233. */
  4234. Vector4.TransformNormal = function (vector, transformation) {
  4235. var result = Vector4.Zero();
  4236. Vector4.TransformNormalToRef(vector, transformation, result);
  4237. return result;
  4238. };
  4239. /**
  4240. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4241. * This methods computes transformed normalized direction vectors only.
  4242. */
  4243. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4244. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4245. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4246. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4247. result.x = x;
  4248. result.y = y;
  4249. result.z = z;
  4250. result.w = vector.w;
  4251. };
  4252. /**
  4253. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4254. * This methods computes transformed normalized direction vectors only.
  4255. */
  4256. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4257. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4258. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4259. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4260. result.w = w;
  4261. };
  4262. return Vector4;
  4263. }());
  4264. BABYLON.Vector4 = Vector4;
  4265. var Size = /** @class */ (function () {
  4266. /**
  4267. * Creates a Size object from the given width and height (floats).
  4268. */
  4269. function Size(width, height) {
  4270. this.width = width;
  4271. this.height = height;
  4272. }
  4273. // Returns a string with the Size width and height.
  4274. Size.prototype.toString = function () {
  4275. return "{W: " + this.width + ", H: " + this.height + "}";
  4276. };
  4277. /**
  4278. * Returns the string "Size"
  4279. */
  4280. Size.prototype.getClassName = function () {
  4281. return "Size";
  4282. };
  4283. /**
  4284. * Returns the Size hash code.
  4285. */
  4286. Size.prototype.getHashCode = function () {
  4287. var hash = this.width || 0;
  4288. hash = (hash * 397) ^ (this.height || 0);
  4289. return hash;
  4290. };
  4291. /**
  4292. * Updates the current size from the given one.
  4293. * Returns the updated Size.
  4294. */
  4295. Size.prototype.copyFrom = function (src) {
  4296. this.width = src.width;
  4297. this.height = src.height;
  4298. };
  4299. /**
  4300. * Updates in place the current Size from the given floats.
  4301. * Returns the updated Size.
  4302. */
  4303. Size.prototype.copyFromFloats = function (width, height) {
  4304. this.width = width;
  4305. this.height = height;
  4306. return this;
  4307. };
  4308. /**
  4309. * Updates in place the current Size from the given floats.
  4310. * Returns the updated Size.
  4311. */
  4312. Size.prototype.set = function (width, height) {
  4313. return this.copyFromFloats(width, height);
  4314. };
  4315. /**
  4316. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4317. */
  4318. Size.prototype.multiplyByFloats = function (w, h) {
  4319. return new Size(this.width * w, this.height * h);
  4320. };
  4321. /**
  4322. * Returns a new Size copied from the given one.
  4323. */
  4324. Size.prototype.clone = function () {
  4325. return new Size(this.width, this.height);
  4326. };
  4327. /**
  4328. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4329. */
  4330. Size.prototype.equals = function (other) {
  4331. if (!other) {
  4332. return false;
  4333. }
  4334. return (this.width === other.width) && (this.height === other.height);
  4335. };
  4336. Object.defineProperty(Size.prototype, "surface", {
  4337. /**
  4338. * Returns the surface of the Size : width * height (float).
  4339. */
  4340. get: function () {
  4341. return this.width * this.height;
  4342. },
  4343. enumerable: true,
  4344. configurable: true
  4345. });
  4346. /**
  4347. * Returns a new Size set to (0.0, 0.0)
  4348. */
  4349. Size.Zero = function () {
  4350. return new Size(0.0, 0.0);
  4351. };
  4352. /**
  4353. * Returns a new Size set as the addition result of the current Size and the given one.
  4354. */
  4355. Size.prototype.add = function (otherSize) {
  4356. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4357. return r;
  4358. };
  4359. /**
  4360. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4361. */
  4362. Size.prototype.subtract = function (otherSize) {
  4363. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4364. return r;
  4365. };
  4366. /**
  4367. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4368. */
  4369. Size.Lerp = function (start, end, amount) {
  4370. var w = start.width + ((end.width - start.width) * amount);
  4371. var h = start.height + ((end.height - start.height) * amount);
  4372. return new Size(w, h);
  4373. };
  4374. return Size;
  4375. }());
  4376. BABYLON.Size = Size;
  4377. /**
  4378. * Class used to store quaternion data
  4379. * @see https://en.wikipedia.org/wiki/Quaternion
  4380. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4381. */
  4382. var Quaternion = /** @class */ (function () {
  4383. /**
  4384. * Creates a new Quaternion from the given floats
  4385. * @param x defines the first component (0 by default)
  4386. * @param y defines the second component (0 by default)
  4387. * @param z defines the third component (0 by default)
  4388. * @param w defines the fourth component (1.0 by default)
  4389. */
  4390. function Quaternion(
  4391. /** defines the first component (0 by default) */
  4392. x,
  4393. /** defines the second component (0 by default) */
  4394. y,
  4395. /** defines the third component (0 by default) */
  4396. z,
  4397. /** defines the fourth component (1.0 by default) */
  4398. w) {
  4399. if (x === void 0) { x = 0.0; }
  4400. if (y === void 0) { y = 0.0; }
  4401. if (z === void 0) { z = 0.0; }
  4402. if (w === void 0) { w = 1.0; }
  4403. this.x = x;
  4404. this.y = y;
  4405. this.z = z;
  4406. this.w = w;
  4407. }
  4408. /**
  4409. * Gets a string representation for the current quaternion
  4410. * @returns a string with the Quaternion coordinates
  4411. */
  4412. Quaternion.prototype.toString = function () {
  4413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4414. };
  4415. /**
  4416. * Gets the class name of the quaternion
  4417. * @returns the string "Quaternion"
  4418. */
  4419. Quaternion.prototype.getClassName = function () {
  4420. return "Quaternion";
  4421. };
  4422. /**
  4423. * Gets a hash code for this quaternion
  4424. * @returns the quaternion hash code
  4425. */
  4426. Quaternion.prototype.getHashCode = function () {
  4427. var hash = this.x || 0;
  4428. hash = (hash * 397) ^ (this.y || 0);
  4429. hash = (hash * 397) ^ (this.z || 0);
  4430. hash = (hash * 397) ^ (this.w || 0);
  4431. return hash;
  4432. };
  4433. /**
  4434. * Copy the quaternion to an array
  4435. * @returns a new array populated with 4 elements from the quaternion coordinates
  4436. */
  4437. Quaternion.prototype.asArray = function () {
  4438. return [this.x, this.y, this.z, this.w];
  4439. };
  4440. /**
  4441. * Check if two quaternions are equals
  4442. * @param otherQuaternion defines the second operand
  4443. * @return true if the current quaternion and the given one coordinates are strictly equals
  4444. */
  4445. Quaternion.prototype.equals = function (otherQuaternion) {
  4446. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4447. };
  4448. /**
  4449. * Clone the current quaternion
  4450. * @returns a new quaternion copied from the current one
  4451. */
  4452. Quaternion.prototype.clone = function () {
  4453. return new Quaternion(this.x, this.y, this.z, this.w);
  4454. };
  4455. /**
  4456. * Copy a quaternion to the current one
  4457. * @param other defines the other quaternion
  4458. * @returns the updated current quaternion
  4459. */
  4460. Quaternion.prototype.copyFrom = function (other) {
  4461. this.x = other.x;
  4462. this.y = other.y;
  4463. this.z = other.z;
  4464. this.w = other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Updates the current quaternion with the given float coordinates
  4469. * @param x defines the x coordinate
  4470. * @param y defines the y coordinate
  4471. * @param z defines the z coordinate
  4472. * @param w defines the w coordinate
  4473. * @returns the updated current quaternion
  4474. */
  4475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4476. this.x = x;
  4477. this.y = y;
  4478. this.z = z;
  4479. this.w = w;
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current quaternion from the given float coordinates
  4484. * @param x defines the x coordinate
  4485. * @param y defines the y coordinate
  4486. * @param z defines the z coordinate
  4487. * @param w defines the w coordinate
  4488. * @returns the updated current quaternion
  4489. */
  4490. Quaternion.prototype.set = function (x, y, z, w) {
  4491. return this.copyFromFloats(x, y, z, w);
  4492. };
  4493. /**
  4494. * Adds two quaternions
  4495. * @param other defines the second operand
  4496. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4497. */
  4498. Quaternion.prototype.add = function (other) {
  4499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4500. };
  4501. /**
  4502. * Add a quaternion to the current one
  4503. * @param other defines the quaternion to add
  4504. * @returns the current quaternion
  4505. */
  4506. Quaternion.prototype.addInPlace = function (other) {
  4507. this.x += other.x;
  4508. this.y += other.y;
  4509. this.z += other.z;
  4510. this.w += other.w;
  4511. return this;
  4512. };
  4513. /**
  4514. * Subtract two quaternions
  4515. * @param other defines the second operand
  4516. * @returns a new quaternion as the subtraction result of the given one from the current one
  4517. */
  4518. Quaternion.prototype.subtract = function (other) {
  4519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4520. };
  4521. /**
  4522. * Multiplies the current quaternion by a scale factor
  4523. * @param value defines the scale factor
  4524. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4525. */
  4526. Quaternion.prototype.scale = function (value) {
  4527. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4528. };
  4529. /**
  4530. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4531. * @param scale defines the scale factor
  4532. * @param result defines the Quaternion object where to store the result
  4533. * @returns the unmodified current quaternion
  4534. */
  4535. Quaternion.prototype.scaleToRef = function (scale, result) {
  4536. result.x = this.x * scale;
  4537. result.y = this.y * scale;
  4538. result.z = this.z * scale;
  4539. result.w = this.w * scale;
  4540. return this;
  4541. };
  4542. /**
  4543. * Multiplies in place the current quaternion by a scale factor
  4544. * @param value defines the scale factor
  4545. * @returns the current modified quaternion
  4546. */
  4547. Quaternion.prototype.scaleInPlace = function (value) {
  4548. this.x *= value;
  4549. this.y *= value;
  4550. this.z *= value;
  4551. this.w *= value;
  4552. return this;
  4553. };
  4554. /**
  4555. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4556. * @param scale defines the scale factor
  4557. * @param result defines the Quaternion object where to store the result
  4558. * @returns the unmodified current quaternion
  4559. */
  4560. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4561. result.x += this.x * scale;
  4562. result.y += this.y * scale;
  4563. result.z += this.z * scale;
  4564. result.w += this.w * scale;
  4565. return this;
  4566. };
  4567. /**
  4568. * Multiplies two quaternions
  4569. * @param q1 defines the second operand
  4570. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4571. */
  4572. Quaternion.prototype.multiply = function (q1) {
  4573. var result = new Quaternion(0, 0, 0, 1.0);
  4574. this.multiplyToRef(q1, result);
  4575. return result;
  4576. };
  4577. /**
  4578. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4579. * @param q1 defines the second operand
  4580. * @param result defines the target quaternion
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4584. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4585. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4586. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4587. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4588. result.copyFromFloats(x, y, z, w);
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4593. * @param q1 defines the second operand
  4594. * @returns the currentupdated quaternion
  4595. */
  4596. Quaternion.prototype.multiplyInPlace = function (q1) {
  4597. this.multiplyToRef(q1, this);
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4602. * @param ref defines the target quaternion
  4603. * @returns the current quaternion
  4604. */
  4605. Quaternion.prototype.conjugateToRef = function (ref) {
  4606. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4607. return this;
  4608. };
  4609. /**
  4610. * Conjugates in place (1-q) the current quaternion
  4611. * @returns the current updated quaternion
  4612. */
  4613. Quaternion.prototype.conjugateInPlace = function () {
  4614. this.x *= -1;
  4615. this.y *= -1;
  4616. this.z *= -1;
  4617. return this;
  4618. };
  4619. /**
  4620. * Conjugates in place (1-q) the current quaternion
  4621. * @returns a new quaternion
  4622. */
  4623. Quaternion.prototype.conjugate = function () {
  4624. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4625. return result;
  4626. };
  4627. /**
  4628. * Gets length of current quaternion
  4629. * @returns the quaternion length (float)
  4630. */
  4631. Quaternion.prototype.length = function () {
  4632. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4633. };
  4634. /**
  4635. * Normalize in place the current quaternion
  4636. * @returns the current updated quaternion
  4637. */
  4638. Quaternion.prototype.normalize = function () {
  4639. var length = 1.0 / this.length();
  4640. this.x *= length;
  4641. this.y *= length;
  4642. this.z *= length;
  4643. this.w *= length;
  4644. return this;
  4645. };
  4646. /**
  4647. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns a new Vector3 containing the Euler angles
  4650. */
  4651. Quaternion.prototype.toEulerAngles = function (order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var result = Vector3.Zero();
  4654. this.toEulerAnglesToRef(result, order);
  4655. return result;
  4656. };
  4657. /**
  4658. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4659. * @param result defines the vector which will be filled with the Euler angles
  4660. * @param order is a reserved parameter and is ignore for now
  4661. * @returns the current unchanged quaternion
  4662. */
  4663. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4664. if (order === void 0) { order = "YZX"; }
  4665. var qz = this.z;
  4666. var qx = this.x;
  4667. var qy = this.y;
  4668. var qw = this.w;
  4669. var sqw = qw * qw;
  4670. var sqz = qz * qz;
  4671. var sqx = qx * qx;
  4672. var sqy = qy * qy;
  4673. var zAxisY = qy * qz - qx * qw;
  4674. var limit = .4999999;
  4675. if (zAxisY < -limit) {
  4676. result.y = 2 * Math.atan2(qy, qw);
  4677. result.x = Math.PI / 2;
  4678. result.z = 0;
  4679. }
  4680. else if (zAxisY > limit) {
  4681. result.y = 2 * Math.atan2(qy, qw);
  4682. result.x = -Math.PI / 2;
  4683. result.z = 0;
  4684. }
  4685. else {
  4686. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4687. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4688. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4689. }
  4690. return this;
  4691. };
  4692. /**
  4693. * Updates the given rotation matrix with the current quaternion values
  4694. * @param result defines the target matrix
  4695. * @returns the current unchanged quaternion
  4696. */
  4697. Quaternion.prototype.toRotationMatrix = function (result) {
  4698. var xx = this.x * this.x;
  4699. var yy = this.y * this.y;
  4700. var zz = this.z * this.z;
  4701. var xy = this.x * this.y;
  4702. var zw = this.z * this.w;
  4703. var zx = this.z * this.x;
  4704. var yw = this.y * this.w;
  4705. var yz = this.y * this.z;
  4706. var xw = this.x * this.w;
  4707. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4708. result.m[1] = 2.0 * (xy + zw);
  4709. result.m[2] = 2.0 * (zx - yw);
  4710. result.m[3] = 0;
  4711. result.m[4] = 2.0 * (xy - zw);
  4712. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4713. result.m[6] = 2.0 * (yz + xw);
  4714. result.m[7] = 0;
  4715. result.m[8] = 2.0 * (zx + yw);
  4716. result.m[9] = 2.0 * (yz - xw);
  4717. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4718. result.m[11] = 0;
  4719. result.m[12] = 0;
  4720. result.m[13] = 0;
  4721. result.m[14] = 0;
  4722. result.m[15] = 1.0;
  4723. result._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Updates the current quaternion from the given rotation matrix values
  4728. * @param matrix defines the source matrix
  4729. * @returns the current updated quaternion
  4730. */
  4731. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4732. Quaternion.FromRotationMatrixToRef(matrix, this);
  4733. return this;
  4734. };
  4735. // Statics
  4736. /**
  4737. * Creates a new quaternion from a rotation matrix
  4738. * @param matrix defines the source matrix
  4739. * @returns a new quaternion created from the given rotation matrix values
  4740. */
  4741. Quaternion.FromRotationMatrix = function (matrix) {
  4742. var result = new Quaternion();
  4743. Quaternion.FromRotationMatrixToRef(matrix, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Updates the given quaternion with the given rotation matrix values
  4748. * @param matrix defines the source matrix
  4749. * @param result defines the target quaternion
  4750. */
  4751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4752. var data = matrix.m;
  4753. var m11 = data[0], m12 = data[4], m13 = data[8];
  4754. var m21 = data[1], m22 = data[5], m23 = data[9];
  4755. var m31 = data[2], m32 = data[6], m33 = data[10];
  4756. var trace = m11 + m22 + m33;
  4757. var s;
  4758. if (trace > 0) {
  4759. s = 0.5 / Math.sqrt(trace + 1.0);
  4760. result.w = 0.25 / s;
  4761. result.x = (m32 - m23) * s;
  4762. result.y = (m13 - m31) * s;
  4763. result.z = (m21 - m12) * s;
  4764. }
  4765. else if (m11 > m22 && m11 > m33) {
  4766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4767. result.w = (m32 - m23) / s;
  4768. result.x = 0.25 * s;
  4769. result.y = (m12 + m21) / s;
  4770. result.z = (m13 + m31) / s;
  4771. }
  4772. else if (m22 > m33) {
  4773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4774. result.w = (m13 - m31) / s;
  4775. result.x = (m12 + m21) / s;
  4776. result.y = 0.25 * s;
  4777. result.z = (m23 + m32) / s;
  4778. }
  4779. else {
  4780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4781. result.w = (m21 - m12) / s;
  4782. result.x = (m13 + m31) / s;
  4783. result.y = (m23 + m32) / s;
  4784. result.z = 0.25 * s;
  4785. }
  4786. };
  4787. /**
  4788. * Returns the dot product (float) between the quaternions "left" and "right"
  4789. * @param left defines the left operand
  4790. * @param right defines the right operand
  4791. * @returns the dot product
  4792. */
  4793. Quaternion.Dot = function (left, right) {
  4794. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4795. };
  4796. /**
  4797. * Checks if the two quaternions are close to each other
  4798. * @param quat0 defines the first quaternion to check
  4799. * @param quat1 defines the second quaternion to check
  4800. * @returns true if the two quaternions are close to each other
  4801. */
  4802. Quaternion.AreClose = function (quat0, quat1) {
  4803. var dot = Quaternion.Dot(quat0, quat1);
  4804. return dot >= 0;
  4805. };
  4806. /**
  4807. * Creates an empty quaternion
  4808. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4809. */
  4810. Quaternion.Zero = function () {
  4811. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. };
  4813. /**
  4814. * Inverse a given quaternion
  4815. * @param q defines the source quaternion
  4816. * @returns a new quaternion as the inverted current quaternion
  4817. */
  4818. Quaternion.Inverse = function (q) {
  4819. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4820. };
  4821. /**
  4822. * Creates an identity quaternion
  4823. * @returns the identity quaternion
  4824. */
  4825. Quaternion.Identity = function () {
  4826. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4827. };
  4828. /**
  4829. * Gets a boolean indicating if the given quaternion is identity
  4830. * @param quaternion defines the quaternion to check
  4831. * @returns true if the quaternion is identity
  4832. */
  4833. Quaternion.IsIdentity = function (quaternion) {
  4834. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4835. };
  4836. /**
  4837. * Creates a quaternion from a rotation around an axis
  4838. * @param axis defines the axis to use
  4839. * @param angle defines the angle to use
  4840. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4841. */
  4842. Quaternion.RotationAxis = function (axis, angle) {
  4843. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4844. };
  4845. /**
  4846. * Creates a rotation around an axis and stores it into the given quaternion
  4847. * @param axis defines the axis to use
  4848. * @param angle defines the angle to use
  4849. * @param result defines the target quaternion
  4850. * @returns the target quaternion
  4851. */
  4852. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4853. var sin = Math.sin(angle / 2);
  4854. axis.normalize();
  4855. result.w = Math.cos(angle / 2);
  4856. result.x = axis.x * sin;
  4857. result.y = axis.y * sin;
  4858. result.z = axis.z * sin;
  4859. return result;
  4860. };
  4861. /**
  4862. * Creates a new quaternion from data stored into an array
  4863. * @param array defines the data source
  4864. * @param offset defines the offset in the source array where the data starts
  4865. * @returns a new quaternion
  4866. */
  4867. Quaternion.FromArray = function (array, offset) {
  4868. if (!offset) {
  4869. offset = 0;
  4870. }
  4871. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4872. };
  4873. /**
  4874. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @returns the new quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4881. var q = new Quaternion();
  4882. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4883. return q;
  4884. };
  4885. /**
  4886. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4887. * @param yaw defines the rotation around Y axis
  4888. * @param pitch defines the rotation around X axis
  4889. * @param roll defines the rotation around Z axis
  4890. * @param result defines the target quaternion
  4891. */
  4892. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4893. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4894. var halfRoll = roll * 0.5;
  4895. var halfPitch = pitch * 0.5;
  4896. var halfYaw = yaw * 0.5;
  4897. var sinRoll = Math.sin(halfRoll);
  4898. var cosRoll = Math.cos(halfRoll);
  4899. var sinPitch = Math.sin(halfPitch);
  4900. var cosPitch = Math.cos(halfPitch);
  4901. var sinYaw = Math.sin(halfYaw);
  4902. var cosYaw = Math.cos(halfYaw);
  4903. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4904. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4905. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4906. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @returns the new quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4916. var result = new Quaternion();
  4917. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4918. return result;
  4919. };
  4920. /**
  4921. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4922. * @param alpha defines the rotation around first axis
  4923. * @param beta defines the rotation around second axis
  4924. * @param gamma defines the rotation around third axis
  4925. * @param result defines the target quaternion
  4926. */
  4927. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4928. // Produces a quaternion from Euler angles in the z-x-z orientation
  4929. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4930. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4931. var halfBeta = beta * 0.5;
  4932. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4933. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4934. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4935. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4936. };
  4937. /**
  4938. * 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)
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @returns the new quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4945. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4946. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4947. return quat;
  4948. };
  4949. /**
  4950. * 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
  4951. * @param axis1 defines the first axis
  4952. * @param axis2 defines the second axis
  4953. * @param axis3 defines the third axis
  4954. * @param ref defines the target quaternion
  4955. */
  4956. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4957. var rotMat = MathTmp.Matrix[0];
  4958. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4959. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @returns the new interpolated quaternion
  4967. */
  4968. Quaternion.Slerp = function (left, right, amount) {
  4969. var result = Quaternion.Identity();
  4970. Quaternion.SlerpToRef(left, right, amount, result);
  4971. return result;
  4972. };
  4973. /**
  4974. * Interpolates between two quaternions and stores it into a target quaternion
  4975. * @param left defines first quaternion
  4976. * @param right defines second quaternion
  4977. * @param amount defines the gradient to use
  4978. * @param result defines the target quaternion
  4979. */
  4980. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4981. var num2;
  4982. var num3;
  4983. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4984. var flag = false;
  4985. if (num4 < 0) {
  4986. flag = true;
  4987. num4 = -num4;
  4988. }
  4989. if (num4 > 0.999999) {
  4990. num3 = 1 - amount;
  4991. num2 = flag ? -amount : amount;
  4992. }
  4993. else {
  4994. var num5 = Math.acos(num4);
  4995. var num6 = (1.0 / Math.sin(num5));
  4996. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4997. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4998. }
  4999. result.x = (num3 * left.x) + (num2 * right.x);
  5000. result.y = (num3 * left.y) + (num2 * right.y);
  5001. result.z = (num3 * left.z) + (num2 * right.z);
  5002. result.w = (num3 * left.w) + (num2 * right.w);
  5003. };
  5004. /**
  5005. * Interpolate between two quaternions using Hermite interpolation
  5006. * @param value1 defines first quaternion
  5007. * @param tangent1 defines the incoming tangent
  5008. * @param value2 defines second quaternion
  5009. * @param tangent2 defines the outgoing tangent
  5010. * @param amount defines the target quaternion
  5011. * @returns the new interpolated quaternion
  5012. */
  5013. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5014. var squared = amount * amount;
  5015. var cubed = amount * squared;
  5016. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5017. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5018. var part3 = (cubed - (2.0 * squared)) + amount;
  5019. var part4 = cubed - squared;
  5020. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5021. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5022. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5023. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5024. return new Quaternion(x, y, z, w);
  5025. };
  5026. return Quaternion;
  5027. }());
  5028. BABYLON.Quaternion = Quaternion;
  5029. /**
  5030. * Class used to store matrix data (4x4)
  5031. */
  5032. var Matrix = /** @class */ (function () {
  5033. /**
  5034. * Creates an empty matrix (filled with zeros)
  5035. */
  5036. function Matrix() {
  5037. this._isIdentity = false;
  5038. this._isIdentityDirty = true;
  5039. /**
  5040. * Gets or sets the internal data of the matrix
  5041. */
  5042. this.m = new Float32Array(16);
  5043. this._markAsUpdated();
  5044. }
  5045. /** @hidden */
  5046. Matrix.prototype._markAsUpdated = function () {
  5047. this.updateFlag = Matrix._updateFlagSeed++;
  5048. this._isIdentityDirty = true;
  5049. };
  5050. // Properties
  5051. /**
  5052. * Check if the current matrix is indentity
  5053. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5054. * @returns true is the matrix is the identity matrix
  5055. */
  5056. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5057. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5058. if (this._isIdentityDirty) {
  5059. this._isIdentityDirty = false;
  5060. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5064. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5065. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5066. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5067. this._isIdentity = false;
  5068. }
  5069. else {
  5070. this._isIdentity = true;
  5071. }
  5072. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5073. this._isIdentity = false;
  5074. }
  5075. }
  5076. return this._isIdentity;
  5077. };
  5078. /**
  5079. * Gets the determinant of the matrix
  5080. * @returns the matrix determinant
  5081. */
  5082. Matrix.prototype.determinant = function () {
  5083. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5084. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5085. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5086. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5087. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5088. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5089. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5090. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5091. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5092. };
  5093. // Methods
  5094. /**
  5095. * Returns the matrix as a Float32Array
  5096. * @returns the matrix underlying array
  5097. */
  5098. Matrix.prototype.toArray = function () {
  5099. return this.m;
  5100. };
  5101. /**
  5102. * Returns the matrix as a Float32Array
  5103. * @returns the matrix underlying array.
  5104. */
  5105. Matrix.prototype.asArray = function () {
  5106. return this.toArray();
  5107. };
  5108. /**
  5109. * Inverts the current matrix in place
  5110. * @returns the current inverted matrix
  5111. */
  5112. Matrix.prototype.invert = function () {
  5113. this.invertToRef(this);
  5114. return this;
  5115. };
  5116. /**
  5117. * Sets all the matrix elements to zero
  5118. * @returns the current matrix
  5119. */
  5120. Matrix.prototype.reset = function () {
  5121. for (var index = 0; index < 16; index++) {
  5122. this.m[index] = 0.0;
  5123. }
  5124. this._markAsUpdated();
  5125. return this;
  5126. };
  5127. /**
  5128. * Adds the current matrix with a second one
  5129. * @param other defines the matrix to add
  5130. * @returns a new matrix as the addition of the current matrix and the given one
  5131. */
  5132. Matrix.prototype.add = function (other) {
  5133. var result = new Matrix();
  5134. this.addToRef(other, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5139. * @param other defines the matrix to add
  5140. * @param result defines the target matrix
  5141. * @returns the current matrix
  5142. */
  5143. Matrix.prototype.addToRef = function (other, result) {
  5144. for (var index = 0; index < 16; index++) {
  5145. result.m[index] = this.m[index] + other.m[index];
  5146. }
  5147. result._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Adds in place the given matrix to the current matrix
  5152. * @param other defines the second operand
  5153. * @returns the current updated matrix
  5154. */
  5155. Matrix.prototype.addToSelf = function (other) {
  5156. for (var index = 0; index < 16; index++) {
  5157. this.m[index] += other.m[index];
  5158. }
  5159. this._markAsUpdated();
  5160. return this;
  5161. };
  5162. /**
  5163. * Sets the given matrix to the current inverted Matrix
  5164. * @param other defines the target matrix
  5165. * @returns the unmodified current matrix
  5166. */
  5167. Matrix.prototype.invertToRef = function (other) {
  5168. var l1 = this.m[0];
  5169. var l2 = this.m[1];
  5170. var l3 = this.m[2];
  5171. var l4 = this.m[3];
  5172. var l5 = this.m[4];
  5173. var l6 = this.m[5];
  5174. var l7 = this.m[6];
  5175. var l8 = this.m[7];
  5176. var l9 = this.m[8];
  5177. var l10 = this.m[9];
  5178. var l11 = this.m[10];
  5179. var l12 = this.m[11];
  5180. var l13 = this.m[12];
  5181. var l14 = this.m[13];
  5182. var l15 = this.m[14];
  5183. var l16 = this.m[15];
  5184. var l17 = (l11 * l16) - (l12 * l15);
  5185. var l18 = (l10 * l16) - (l12 * l14);
  5186. var l19 = (l10 * l15) - (l11 * l14);
  5187. var l20 = (l9 * l16) - (l12 * l13);
  5188. var l21 = (l9 * l15) - (l11 * l13);
  5189. var l22 = (l9 * l14) - (l10 * l13);
  5190. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5191. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5192. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5193. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5194. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5195. var l28 = (l7 * l16) - (l8 * l15);
  5196. var l29 = (l6 * l16) - (l8 * l14);
  5197. var l30 = (l6 * l15) - (l7 * l14);
  5198. var l31 = (l5 * l16) - (l8 * l13);
  5199. var l32 = (l5 * l15) - (l7 * l13);
  5200. var l33 = (l5 * l14) - (l6 * l13);
  5201. var l34 = (l7 * l12) - (l8 * l11);
  5202. var l35 = (l6 * l12) - (l8 * l10);
  5203. var l36 = (l6 * l11) - (l7 * l10);
  5204. var l37 = (l5 * l12) - (l8 * l9);
  5205. var l38 = (l5 * l11) - (l7 * l9);
  5206. var l39 = (l5 * l10) - (l6 * l9);
  5207. other.m[0] = l23 * l27;
  5208. other.m[4] = l24 * l27;
  5209. other.m[8] = l25 * l27;
  5210. other.m[12] = l26 * l27;
  5211. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5212. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5213. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5214. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5215. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5216. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5217. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5218. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5219. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5220. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5221. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5222. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5223. other._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Inserts the translation vector (using 3 floats) in the current matrix
  5228. * @param x defines the 1st component of the translation
  5229. * @param y defines the 2nd component of the translation
  5230. * @param z defines the 3rd component of the translation
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5234. this.m[12] = x;
  5235. this.m[13] = y;
  5236. this.m[14] = z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Inserts the translation vector in the current matrix
  5242. * @param vector3 defines the translation to insert
  5243. * @returns the current updated matrix
  5244. */
  5245. Matrix.prototype.setTranslation = function (vector3) {
  5246. this.m[12] = vector3.x;
  5247. this.m[13] = vector3.y;
  5248. this.m[14] = vector3.z;
  5249. this._markAsUpdated();
  5250. return this;
  5251. };
  5252. /**
  5253. * Gets the translation value of the current matrix
  5254. * @returns a new Vector3 as the extracted translation from the matrix
  5255. */
  5256. Matrix.prototype.getTranslation = function () {
  5257. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5258. };
  5259. /**
  5260. * Fill a Vector3 with the extracted translation from the matrix
  5261. * @param result defines the Vector3 where to store the translation
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.getTranslationToRef = function (result) {
  5265. result.x = this.m[12];
  5266. result.y = this.m[13];
  5267. result.z = this.m[14];
  5268. return this;
  5269. };
  5270. /**
  5271. * Remove rotation and scaling part from the matrix
  5272. * @returns the updated matrix
  5273. */
  5274. Matrix.prototype.removeRotationAndScaling = function () {
  5275. this.setRowFromFloats(0, 1, 0, 0, 0);
  5276. this.setRowFromFloats(1, 0, 1, 0, 0);
  5277. this.setRowFromFloats(2, 0, 0, 1, 0);
  5278. return this;
  5279. };
  5280. /**
  5281. * Multiply two matrices
  5282. * @param other defines the second operand
  5283. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5284. */
  5285. Matrix.prototype.multiply = function (other) {
  5286. var result = new Matrix();
  5287. this.multiplyToRef(other, result);
  5288. return result;
  5289. };
  5290. /**
  5291. * Copy the current matrix from the given one
  5292. * @param other defines the source matrix
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.copyFrom = function (other) {
  5296. for (var index = 0; index < 16; index++) {
  5297. this.m[index] = other.m[index];
  5298. }
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Populates the given array from the starting index with the current matrix values
  5304. * @param array defines the target array
  5305. * @param offset defines the offset in the target array where to start storing values
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.copyToArray = function (array, offset) {
  5309. if (offset === void 0) { offset = 0; }
  5310. for (var index = 0; index < 16; index++) {
  5311. array[offset + index] = this.m[index];
  5312. }
  5313. return this;
  5314. };
  5315. /**
  5316. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5317. * @param other defines the second operand
  5318. * @param result defines the matrix where to store the multiplication
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToRef = function (other, result) {
  5322. this.multiplyToArray(other, result.m, 0);
  5323. result._markAsUpdated();
  5324. return this;
  5325. };
  5326. /**
  5327. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5328. * @param other defines the second operand
  5329. * @param result defines the array where to store the multiplication
  5330. * @param offset defines the offset in the target array where to start storing values
  5331. * @returns the current matrix
  5332. */
  5333. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5334. var tm0 = this.m[0];
  5335. var tm1 = this.m[1];
  5336. var tm2 = this.m[2];
  5337. var tm3 = this.m[3];
  5338. var tm4 = this.m[4];
  5339. var tm5 = this.m[5];
  5340. var tm6 = this.m[6];
  5341. var tm7 = this.m[7];
  5342. var tm8 = this.m[8];
  5343. var tm9 = this.m[9];
  5344. var tm10 = this.m[10];
  5345. var tm11 = this.m[11];
  5346. var tm12 = this.m[12];
  5347. var tm13 = this.m[13];
  5348. var tm14 = this.m[14];
  5349. var tm15 = this.m[15];
  5350. var om0 = other.m[0];
  5351. var om1 = other.m[1];
  5352. var om2 = other.m[2];
  5353. var om3 = other.m[3];
  5354. var om4 = other.m[4];
  5355. var om5 = other.m[5];
  5356. var om6 = other.m[6];
  5357. var om7 = other.m[7];
  5358. var om8 = other.m[8];
  5359. var om9 = other.m[9];
  5360. var om10 = other.m[10];
  5361. var om11 = other.m[11];
  5362. var om12 = other.m[12];
  5363. var om13 = other.m[13];
  5364. var om14 = other.m[14];
  5365. var om15 = other.m[15];
  5366. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5367. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5368. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5369. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5370. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5371. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5372. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5373. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5374. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5375. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5376. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5377. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5378. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5379. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5380. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5381. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5382. return this;
  5383. };
  5384. /**
  5385. * Check equality between this matrix and a second one
  5386. * @param value defines the second matrix to compare
  5387. * @returns true is the current matrix and the given one values are strictly equal
  5388. */
  5389. Matrix.prototype.equals = function (value) {
  5390. return value &&
  5391. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5392. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5393. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5394. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5395. };
  5396. /**
  5397. * Clone the current matrix
  5398. * @returns a new matrix from the current matrix
  5399. */
  5400. Matrix.prototype.clone = function () {
  5401. 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]);
  5402. };
  5403. /**
  5404. * Returns the name of the current matrix class
  5405. * @returns the string "Matrix"
  5406. */
  5407. Matrix.prototype.getClassName = function () {
  5408. return "Matrix";
  5409. };
  5410. /**
  5411. * Gets the hash code of the current matrix
  5412. * @returns the hash code
  5413. */
  5414. Matrix.prototype.getHashCode = function () {
  5415. var hash = this.m[0] || 0;
  5416. for (var i = 1; i < 16; i++) {
  5417. hash = (hash * 397) ^ (this.m[i] || 0);
  5418. }
  5419. return hash;
  5420. };
  5421. /**
  5422. * Decomposes the current Matrix into a translation, rotation and scaling components
  5423. * @param scale defines the scale vector3 given as a reference to update
  5424. * @param rotation defines the rotation quaternion given as a reference to update
  5425. * @param translation defines the translation vector3 given as a reference to update
  5426. * @returns true if operation was successful
  5427. */
  5428. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5429. if (translation) {
  5430. translation.x = this.m[12];
  5431. translation.y = this.m[13];
  5432. translation.z = this.m[14];
  5433. }
  5434. scale = scale || MathTmp.Vector3[0];
  5435. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5436. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5437. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5438. if (this.determinant() <= 0) {
  5439. scale.y *= -1;
  5440. }
  5441. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5442. if (rotation) {
  5443. rotation.x = 0;
  5444. rotation.y = 0;
  5445. rotation.z = 0;
  5446. rotation.w = 1;
  5447. }
  5448. return false;
  5449. }
  5450. if (rotation) {
  5451. 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]);
  5452. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5453. }
  5454. return true;
  5455. };
  5456. /**
  5457. * Gets specific row of the matrix
  5458. * @param index defines the number of the row to get
  5459. * @returns the index-th row of the current matrix as a new Vector4
  5460. */
  5461. Matrix.prototype.getRow = function (index) {
  5462. if (index < 0 || index > 3) {
  5463. return null;
  5464. }
  5465. var i = index * 4;
  5466. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5467. };
  5468. /**
  5469. * Sets the index-th row of the current matrix to the vector4 values
  5470. * @param index defines the number of the row to set
  5471. * @param row defines the target vector4
  5472. * @returns the updated current matrix
  5473. */
  5474. Matrix.prototype.setRow = function (index, row) {
  5475. if (index < 0 || index > 3) {
  5476. return this;
  5477. }
  5478. var i = index * 4;
  5479. this.m[i + 0] = row.x;
  5480. this.m[i + 1] = row.y;
  5481. this.m[i + 2] = row.z;
  5482. this.m[i + 3] = row.w;
  5483. this._markAsUpdated();
  5484. return this;
  5485. };
  5486. /**
  5487. * Compute the transpose of the matrix
  5488. * @returns the new transposed matrix
  5489. */
  5490. Matrix.prototype.transpose = function () {
  5491. return Matrix.Transpose(this);
  5492. };
  5493. /**
  5494. * Compute the transpose of the matrix and store it in a given matrix
  5495. * @param result defines the target matrix
  5496. * @returns the current matrix
  5497. */
  5498. Matrix.prototype.transposeToRef = function (result) {
  5499. Matrix.TransposeToRef(this, result);
  5500. return this;
  5501. };
  5502. /**
  5503. * Sets the index-th row of the current matrix with the given 4 x float values
  5504. * @param index defines the row index
  5505. * @param x defines the x component to set
  5506. * @param y defines the y component to set
  5507. * @param z defines the z component to set
  5508. * @param w defines the w component to set
  5509. * @returns the updated current matrix
  5510. */
  5511. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5512. if (index < 0 || index > 3) {
  5513. return this;
  5514. }
  5515. var i = index * 4;
  5516. this.m[i + 0] = x;
  5517. this.m[i + 1] = y;
  5518. this.m[i + 2] = z;
  5519. this.m[i + 3] = w;
  5520. this._markAsUpdated();
  5521. return this;
  5522. };
  5523. /**
  5524. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5525. * @param scale defines the scale factor
  5526. * @returns a new matrix
  5527. */
  5528. Matrix.prototype.scale = function (scale) {
  5529. var result = new Matrix();
  5530. this.scaleToRef(scale, result);
  5531. return result;
  5532. };
  5533. /**
  5534. * Scale the current matrix values by a factor to a given result matrix
  5535. * @param scale defines the scale factor
  5536. * @param result defines the matrix to store the result
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.scaleToRef = function (scale, result) {
  5540. for (var index = 0; index < 16; index++) {
  5541. result.m[index] = this.m[index] * scale;
  5542. }
  5543. result._markAsUpdated();
  5544. return this;
  5545. };
  5546. /**
  5547. * Scale the current matrix values by a factor and add the result to a given matrix
  5548. * @param scale defines the scale factor
  5549. * @param result defines the Matrix to store the result
  5550. * @returns the current matrix
  5551. */
  5552. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5553. for (var index = 0; index < 16; index++) {
  5554. result.m[index] += this.m[index] * scale;
  5555. }
  5556. result._markAsUpdated();
  5557. return this;
  5558. };
  5559. /**
  5560. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5561. * @param ref matrix to store the result
  5562. */
  5563. Matrix.prototype.toNormalMatrix = function (ref) {
  5564. this.invertToRef(ref);
  5565. ref.transpose();
  5566. var m = ref.m;
  5567. 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);
  5568. };
  5569. /**
  5570. * Gets only rotation part of the current matrix
  5571. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5572. */
  5573. Matrix.prototype.getRotationMatrix = function () {
  5574. var result = Matrix.Identity();
  5575. this.getRotationMatrixToRef(result);
  5576. return result;
  5577. };
  5578. /**
  5579. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5580. * @param result defines the target matrix to store data to
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5584. var m = this.m;
  5585. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5586. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5587. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5588. if (this.determinant() <= 0) {
  5589. sy *= -1;
  5590. }
  5591. if (sx === 0 || sy === 0 || sz === 0) {
  5592. Matrix.IdentityToRef(result);
  5593. }
  5594. else {
  5595. 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);
  5596. }
  5597. return this;
  5598. };
  5599. // Statics
  5600. /**
  5601. * Creates a matrix from an array
  5602. * @param array defines the source array
  5603. * @param offset defines an offset in the source array
  5604. * @returns a new Matrix set from the starting index of the given array
  5605. */
  5606. Matrix.FromArray = function (array, offset) {
  5607. var result = new Matrix();
  5608. if (!offset) {
  5609. offset = 0;
  5610. }
  5611. Matrix.FromArrayToRef(array, offset, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Copy the content of an array into a given matrix
  5616. * @param array defines the source array
  5617. * @param offset defines an offset in the source array
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromArrayToRef = function (array, offset, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = array[index + offset];
  5623. }
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Stores an array into a matrix after having multiplied each component by a given factor
  5628. * @param array defines the source array
  5629. * @param offset defines the offset in the source array
  5630. * @param scale defines the scaling factor
  5631. * @param result defines the target matrix
  5632. */
  5633. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] = array[index + offset] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. };
  5639. /**
  5640. * Stores a list of values (16) inside a given matrix
  5641. * @param initialM11 defines 1st value of 1st row
  5642. * @param initialM12 defines 2nd value of 1st row
  5643. * @param initialM13 defines 3rd value of 1st row
  5644. * @param initialM14 defines 4th value of 1st row
  5645. * @param initialM21 defines 1st value of 2nd row
  5646. * @param initialM22 defines 2nd value of 2nd row
  5647. * @param initialM23 defines 3rd value of 2nd row
  5648. * @param initialM24 defines 4th value of 2nd row
  5649. * @param initialM31 defines 1st value of 3rd row
  5650. * @param initialM32 defines 2nd value of 3rd row
  5651. * @param initialM33 defines 3rd value of 3rd row
  5652. * @param initialM34 defines 4th value of 3rd row
  5653. * @param initialM41 defines 1st value of 4th row
  5654. * @param initialM42 defines 2nd value of 4th row
  5655. * @param initialM43 defines 3rd value of 4th row
  5656. * @param initialM44 defines 4th value of 4th row
  5657. * @param result defines the target matrix
  5658. */
  5659. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5660. result.m[0] = initialM11;
  5661. result.m[1] = initialM12;
  5662. result.m[2] = initialM13;
  5663. result.m[3] = initialM14;
  5664. result.m[4] = initialM21;
  5665. result.m[5] = initialM22;
  5666. result.m[6] = initialM23;
  5667. result.m[7] = initialM24;
  5668. result.m[8] = initialM31;
  5669. result.m[9] = initialM32;
  5670. result.m[10] = initialM33;
  5671. result.m[11] = initialM34;
  5672. result.m[12] = initialM41;
  5673. result.m[13] = initialM42;
  5674. result.m[14] = initialM43;
  5675. result.m[15] = initialM44;
  5676. result._markAsUpdated();
  5677. };
  5678. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5679. /**
  5680. * Gets an identity matrix that must not be updated
  5681. */
  5682. get: function () {
  5683. return Matrix._identityReadOnly;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. /**
  5689. * Creates new matrix from a list of values (16)
  5690. * @param initialM11 defines 1st value of 1st row
  5691. * @param initialM12 defines 2nd value of 1st row
  5692. * @param initialM13 defines 3rd value of 1st row
  5693. * @param initialM14 defines 4th value of 1st row
  5694. * @param initialM21 defines 1st value of 2nd row
  5695. * @param initialM22 defines 2nd value of 2nd row
  5696. * @param initialM23 defines 3rd value of 2nd row
  5697. * @param initialM24 defines 4th value of 2nd row
  5698. * @param initialM31 defines 1st value of 3rd row
  5699. * @param initialM32 defines 2nd value of 3rd row
  5700. * @param initialM33 defines 3rd value of 3rd row
  5701. * @param initialM34 defines 4th value of 3rd row
  5702. * @param initialM41 defines 1st value of 4th row
  5703. * @param initialM42 defines 2nd value of 4th row
  5704. * @param initialM43 defines 3rd value of 4th row
  5705. * @param initialM44 defines 4th value of 4th row
  5706. * @returns the new matrix
  5707. */
  5708. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5709. var result = new Matrix();
  5710. result.m[0] = initialM11;
  5711. result.m[1] = initialM12;
  5712. result.m[2] = initialM13;
  5713. result.m[3] = initialM14;
  5714. result.m[4] = initialM21;
  5715. result.m[5] = initialM22;
  5716. result.m[6] = initialM23;
  5717. result.m[7] = initialM24;
  5718. result.m[8] = initialM31;
  5719. result.m[9] = initialM32;
  5720. result.m[10] = initialM33;
  5721. result.m[11] = initialM34;
  5722. result.m[12] = initialM41;
  5723. result.m[13] = initialM42;
  5724. result.m[14] = initialM43;
  5725. result.m[15] = initialM44;
  5726. return result;
  5727. };
  5728. /**
  5729. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @returns a new matrix
  5734. */
  5735. Matrix.Compose = function (scale, rotation, translation) {
  5736. var result = Matrix.Identity();
  5737. Matrix.ComposeToRef(scale, rotation, translation, result);
  5738. return result;
  5739. };
  5740. /**
  5741. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5742. * @param scale defines the scale vector3
  5743. * @param rotation defines the rotation quaternion
  5744. * @param translation defines the translation vector3
  5745. * @param result defines the target matrix
  5746. */
  5747. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5748. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5749. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5750. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5751. result.setTranslation(translation);
  5752. };
  5753. /**
  5754. * Creates a new identity matrix
  5755. * @returns a new identity matrix
  5756. */
  5757. Matrix.Identity = function () {
  5758. 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);
  5759. };
  5760. /**
  5761. * Creates a new identity matrix and stores the result in a given matrix
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.IdentityToRef = function (result) {
  5765. 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);
  5766. };
  5767. /**
  5768. * Creates a new zero matrix
  5769. * @returns a new zero matrix
  5770. */
  5771. Matrix.Zero = function () {
  5772. 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);
  5773. };
  5774. /**
  5775. * Creates a new rotation matrix for "angle" radians around the X axis
  5776. * @param angle defines the angle (in radians) to use
  5777. * @return the new matrix
  5778. */
  5779. Matrix.RotationX = function (angle) {
  5780. var result = new Matrix();
  5781. Matrix.RotationXToRef(angle, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Creates a new matrix as the invert of a given matrix
  5786. * @param source defines the source matrix
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.Invert = function (source) {
  5790. var result = new Matrix();
  5791. source.invertToRef(result);
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5796. * @param angle defines the angle (in radians) to use
  5797. * @param result defines the target matrix
  5798. */
  5799. Matrix.RotationXToRef = function (angle, result) {
  5800. var s = Math.sin(angle);
  5801. var c = Math.cos(angle);
  5802. result.m[0] = 1.0;
  5803. result.m[15] = 1.0;
  5804. result.m[5] = c;
  5805. result.m[10] = c;
  5806. result.m[9] = -s;
  5807. result.m[6] = s;
  5808. result.m[1] = 0.0;
  5809. result.m[2] = 0.0;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = 0.0;
  5812. result.m[7] = 0.0;
  5813. result.m[8] = 0.0;
  5814. result.m[11] = 0.0;
  5815. result.m[12] = 0.0;
  5816. result.m[13] = 0.0;
  5817. result.m[14] = 0.0;
  5818. result._markAsUpdated();
  5819. };
  5820. /**
  5821. * Creates a new rotation matrix for "angle" radians around the Y axis
  5822. * @param angle defines the angle (in radians) to use
  5823. * @return the new matrix
  5824. */
  5825. Matrix.RotationY = function (angle) {
  5826. var result = new Matrix();
  5827. Matrix.RotationYToRef(angle, result);
  5828. return result;
  5829. };
  5830. /**
  5831. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5832. * @param angle defines the angle (in radians) to use
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.RotationYToRef = function (angle, result) {
  5836. var s = Math.sin(angle);
  5837. var c = Math.cos(angle);
  5838. result.m[5] = 1.0;
  5839. result.m[15] = 1.0;
  5840. result.m[0] = c;
  5841. result.m[2] = -s;
  5842. result.m[8] = s;
  5843. result.m[10] = c;
  5844. result.m[1] = 0.0;
  5845. result.m[3] = 0.0;
  5846. result.m[4] = 0.0;
  5847. result.m[6] = 0.0;
  5848. result.m[7] = 0.0;
  5849. result.m[9] = 0.0;
  5850. result.m[11] = 0.0;
  5851. result.m[12] = 0.0;
  5852. result.m[13] = 0.0;
  5853. result.m[14] = 0.0;
  5854. result._markAsUpdated();
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the Z axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationZ = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationZToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationZToRef = function (angle, result) {
  5872. var s = Math.sin(angle);
  5873. var c = Math.cos(angle);
  5874. result.m[10] = 1.0;
  5875. result.m[15] = 1.0;
  5876. result.m[0] = c;
  5877. result.m[1] = s;
  5878. result.m[4] = -s;
  5879. result.m[5] = c;
  5880. result.m[2] = 0.0;
  5881. result.m[3] = 0.0;
  5882. result.m[6] = 0.0;
  5883. result.m[7] = 0.0;
  5884. result.m[8] = 0.0;
  5885. result.m[9] = 0.0;
  5886. result.m[11] = 0.0;
  5887. result.m[12] = 0.0;
  5888. result.m[13] = 0.0;
  5889. result.m[14] = 0.0;
  5890. result._markAsUpdated();
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the given axis
  5894. * @param axis defines the axis to use
  5895. * @param angle defines the angle (in radians) to use
  5896. * @return the new matrix
  5897. */
  5898. Matrix.RotationAxis = function (axis, angle) {
  5899. var result = Matrix.Zero();
  5900. Matrix.RotationAxisToRef(axis, angle, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5905. * @param axis defines the axis to use
  5906. * @param angle defines the angle (in radians) to use
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5910. var s = Math.sin(-angle);
  5911. var c = Math.cos(-angle);
  5912. var c1 = 1 - c;
  5913. axis.normalize();
  5914. result.m[0] = (axis.x * axis.x) * c1 + c;
  5915. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5916. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5917. result.m[3] = 0.0;
  5918. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5919. result.m[5] = (axis.y * axis.y) * c1 + c;
  5920. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5921. result.m[7] = 0.0;
  5922. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5923. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5924. result.m[10] = (axis.z * axis.z) * c1 + c;
  5925. result.m[11] = 0.0;
  5926. result.m[15] = 1.0;
  5927. result._markAsUpdated();
  5928. };
  5929. /**
  5930. * Creates a rotation matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @returns the new rotation matrix
  5935. */
  5936. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5937. var result = new Matrix();
  5938. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Creates a rotation matrix and stores it in a given matrix
  5943. * @param yaw defines the yaw angle in radians (Y axis)
  5944. * @param pitch defines the pitch angle in radians (X axis)
  5945. * @param roll defines the roll angle in radians (X axis)
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5949. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5950. this._tempQuaternion.toRotationMatrix(result);
  5951. };
  5952. /**
  5953. * Creates a scaling matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Scaling = function (x, y, z) {
  5960. var result = Matrix.Zero();
  5961. Matrix.ScalingToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a scaling matrix and stores it in a given matrix
  5966. * @param x defines the scale factor on X axis
  5967. * @param y defines the scale factor on Y axis
  5968. * @param z defines the scale factor on Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.ScalingToRef = function (x, y, z, result) {
  5972. result.m[0] = x;
  5973. result.m[1] = 0.0;
  5974. result.m[2] = 0.0;
  5975. result.m[3] = 0.0;
  5976. result.m[4] = 0.0;
  5977. result.m[5] = y;
  5978. result.m[6] = 0.0;
  5979. result.m[7] = 0.0;
  5980. result.m[8] = 0.0;
  5981. result.m[9] = 0.0;
  5982. result.m[10] = z;
  5983. result.m[11] = 0.0;
  5984. result.m[12] = 0.0;
  5985. result.m[13] = 0.0;
  5986. result.m[14] = 0.0;
  5987. result.m[15] = 1.0;
  5988. result._markAsUpdated();
  5989. };
  5990. /**
  5991. * Creates a translation matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @returns the new matrix
  5996. */
  5997. Matrix.Translation = function (x, y, z) {
  5998. var result = Matrix.Identity();
  5999. Matrix.TranslationToRef(x, y, z, result);
  6000. return result;
  6001. };
  6002. /**
  6003. * Creates a translation matrix and stores it in a given matrix
  6004. * @param x defines the translation on X axis
  6005. * @param y defines the translation on Y axis
  6006. * @param z defines the translationon Z axis
  6007. * @param result defines the target matrix
  6008. */
  6009. Matrix.TranslationToRef = function (x, y, z, result) {
  6010. 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);
  6011. };
  6012. /**
  6013. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @returns the new matrix
  6018. */
  6019. Matrix.Lerp = function (startValue, endValue, gradient) {
  6020. var result = Matrix.Zero();
  6021. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6022. return result;
  6023. };
  6024. /**
  6025. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6026. * @param startValue defines the start value
  6027. * @param endValue defines the end value
  6028. * @param gradient defines the gradient factor
  6029. * @param result defines the Matrix object where to store data
  6030. */
  6031. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6032. for (var index = 0; index < 16; index++) {
  6033. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6034. }
  6035. result._markAsUpdated();
  6036. };
  6037. /**
  6038. * Builds a new matrix whose values are computed by:
  6039. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6040. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6041. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6042. * @param startValue defines the first matrix
  6043. * @param endValue defines the second matrix
  6044. * @param gradient defines the gradient between the two matrices
  6045. * @returns the new matrix
  6046. */
  6047. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6048. var result = Matrix.Zero();
  6049. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6050. return result;
  6051. };
  6052. /**
  6053. * Update a matrix to values which are computed by:
  6054. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6055. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6056. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6057. * @param startValue defines the first matrix
  6058. * @param endValue defines the second matrix
  6059. * @param gradient defines the gradient between the two matrices
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6063. var startScale = MathTmp.Vector3[0];
  6064. var startRotation = MathTmp.Quaternion[0];
  6065. var startTranslation = MathTmp.Vector3[1];
  6066. startValue.decompose(startScale, startRotation, startTranslation);
  6067. var endScale = MathTmp.Vector3[2];
  6068. var endRotation = MathTmp.Quaternion[1];
  6069. var endTranslation = MathTmp.Vector3[3];
  6070. endValue.decompose(endScale, endRotation, endTranslation);
  6071. var resultScale = MathTmp.Vector3[4];
  6072. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6073. var resultRotation = MathTmp.Quaternion[2];
  6074. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6075. var resultTranslation = MathTmp.Vector3[5];
  6076. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6077. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6078. };
  6079. /**
  6080. * 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"
  6081. * This function works in left handed mode
  6082. * @param eye defines the final position of the entity
  6083. * @param target defines where the entity should look at
  6084. * @param up defines the up vector for the entity
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.LookAtLH = function (eye, target, up) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LookAtLHToRef(eye, target, up, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * 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".
  6094. * This function works in left handed mode
  6095. * @param eye defines the final position of the entity
  6096. * @param target defines where the entity should look at
  6097. * @param up defines the up vector for the entity
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6101. // Z axis
  6102. target.subtractToRef(eye, this._zAxis);
  6103. this._zAxis.normalize();
  6104. // X axis
  6105. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6106. if (this._xAxis.lengthSquared() === 0) {
  6107. this._xAxis.x = 1.0;
  6108. }
  6109. else {
  6110. this._xAxis.normalize();
  6111. }
  6112. // Y axis
  6113. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6114. this._yAxis.normalize();
  6115. // Eye angles
  6116. var ex = -Vector3.Dot(this._xAxis, eye);
  6117. var ey = -Vector3.Dot(this._yAxis, eye);
  6118. var ez = -Vector3.Dot(this._zAxis, eye);
  6119. 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);
  6120. };
  6121. /**
  6122. * 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"
  6123. * This function works in right handed mode
  6124. * @param eye defines the final position of the entity
  6125. * @param target defines where the entity should look at
  6126. * @param up defines the up vector for the entity
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.LookAtRH = function (eye, target, up) {
  6130. var result = Matrix.Zero();
  6131. Matrix.LookAtRHToRef(eye, target, up, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * 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".
  6136. * This function works in right handed mode
  6137. * @param eye defines the final position of the entity
  6138. * @param target defines where the entity should look at
  6139. * @param up defines the up vector for the entity
  6140. * @param result defines the target matrix
  6141. */
  6142. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6143. // Z axis
  6144. eye.subtractToRef(target, this._zAxis);
  6145. this._zAxis.normalize();
  6146. // X axis
  6147. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6148. if (this._xAxis.lengthSquared() === 0) {
  6149. this._xAxis.x = 1.0;
  6150. }
  6151. else {
  6152. this._xAxis.normalize();
  6153. }
  6154. // Y axis
  6155. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6156. this._yAxis.normalize();
  6157. // Eye angles
  6158. var ex = -Vector3.Dot(this._xAxis, eye);
  6159. var ey = -Vector3.Dot(this._yAxis, eye);
  6160. var ez = -Vector3.Dot(this._zAxis, eye);
  6161. 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);
  6162. };
  6163. /**
  6164. * Create a left-handed orthographic projection matrix
  6165. * @param width defines the viewport width
  6166. * @param height defines the viewport height
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Store a left-handed orthographic projection to a given matrix
  6178. * @param width defines the viewport width
  6179. * @param height defines the viewport height
  6180. * @param znear defines the near clip plane
  6181. * @param zfar defines the far clip plane
  6182. * @param result defines the target matrix
  6183. */
  6184. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6185. var n = znear;
  6186. var f = zfar;
  6187. var a = 2.0 / width;
  6188. var b = 2.0 / height;
  6189. var c = 2.0 / (f - n);
  6190. var d = -(f + n) / (f - n);
  6191. 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);
  6192. };
  6193. /**
  6194. * Create a left-handed orthographic projection matrix
  6195. * @param left defines the viewport left coordinate
  6196. * @param right defines the viewport right coordinate
  6197. * @param bottom defines the viewport bottom coordinate
  6198. * @param top defines the viewport top coordinate
  6199. * @param znear defines the near clip plane
  6200. * @param zfar defines the far clip plane
  6201. * @returns a new matrix as a left-handed orthographic projection matrix
  6202. */
  6203. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6204. var matrix = Matrix.Zero();
  6205. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6206. return matrix;
  6207. };
  6208. /**
  6209. * Stores a left-handed orthographic projection into a given matrix
  6210. * @param left defines the viewport left coordinate
  6211. * @param right defines the viewport right coordinate
  6212. * @param bottom defines the viewport bottom coordinate
  6213. * @param top defines the viewport top coordinate
  6214. * @param znear defines the near clip plane
  6215. * @param zfar defines the far clip plane
  6216. * @param result defines the target matrix
  6217. */
  6218. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6219. var n = znear;
  6220. var f = zfar;
  6221. var a = 2.0 / (right - left);
  6222. var b = 2.0 / (top - bottom);
  6223. var c = 2.0 / (f - n);
  6224. var d = -(f + n) / (f - n);
  6225. var i0 = (left + right) / (left - right);
  6226. var i1 = (top + bottom) / (bottom - top);
  6227. 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);
  6228. };
  6229. /**
  6230. * Creates a right-handed orthographic projection matrix
  6231. * @param left defines the viewport left coordinate
  6232. * @param right defines the viewport right coordinate
  6233. * @param bottom defines the viewport bottom coordinate
  6234. * @param top defines the viewport top coordinate
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a right-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Stores a right-handed orthographic projection into a given matrix
  6246. * @param left defines the viewport left coordinate
  6247. * @param right defines the viewport right coordinate
  6248. * @param bottom defines the viewport bottom coordinate
  6249. * @param top defines the viewport top coordinate
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6255. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6256. result.m[10] *= -1.0;
  6257. };
  6258. /**
  6259. * Creates a left-handed perspective projection matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @returns a new matrix as a left-handed perspective projection matrix
  6265. */
  6266. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6267. var matrix = Matrix.Zero();
  6268. var n = znear;
  6269. var f = zfar;
  6270. var a = 2.0 * n / width;
  6271. var b = 2.0 * n / height;
  6272. var c = (f + n) / (f - n);
  6273. var d = -2.0 * f * n / (f - n);
  6274. 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);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Creates a left-handed perspective projection matrix
  6279. * @param fov defines the horizontal field of view
  6280. * @param aspect defines the aspect ratio
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed perspective projection matrix
  6284. */
  6285. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed perspective projection into a given matrix
  6292. * @param fov defines the horizontal field of view
  6293. * @param aspect defines the aspect ratio
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6298. */
  6299. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6300. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6301. var n = znear;
  6302. var f = zfar;
  6303. var t = 1.0 / (Math.tan(fov * 0.5));
  6304. var a = isVerticalFovFixed ? (t / aspect) : t;
  6305. var b = isVerticalFovFixed ? t : (t * aspect);
  6306. var c = (f + n) / (f - n);
  6307. var d = -2.0 * f * n / (f - n);
  6308. 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);
  6309. };
  6310. /**
  6311. * Creates a right-handed perspective projection matrix
  6312. * @param fov defines the horizontal field of view
  6313. * @param aspect defines the aspect ratio
  6314. * @param znear defines the near clip plane
  6315. * @param zfar defines the far clip plane
  6316. * @returns a new matrix as a right-handed perspective projection matrix
  6317. */
  6318. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6319. var matrix = Matrix.Zero();
  6320. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6321. return matrix;
  6322. };
  6323. /**
  6324. * Stores a right-handed perspective projection into a given matrix
  6325. * @param fov defines the horizontal field of view
  6326. * @param aspect defines the aspect ratio
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6331. */
  6332. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6333. //alternatively this could be expressed as:
  6334. // m = PerspectiveFovLHToRef
  6335. // m[10] *= -1.0;
  6336. // m[11] *= -1.0;
  6337. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6338. var n = znear;
  6339. var f = zfar;
  6340. var t = 1.0 / (Math.tan(fov * 0.5));
  6341. var a = isVerticalFovFixed ? (t / aspect) : t;
  6342. var b = isVerticalFovFixed ? t : (t * aspect);
  6343. var c = -(f + n) / (f - n);
  6344. var d = -2 * f * n / (f - n);
  6345. 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);
  6346. };
  6347. /**
  6348. * Stores a perspective projection for WebVR info a given matrix
  6349. * @param fov defines the field of view
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @param result defines the target matrix
  6353. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6354. */
  6355. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6356. if (rightHanded === void 0) { rightHanded = false; }
  6357. var rightHandedFactor = rightHanded ? -1 : 1;
  6358. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6359. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6360. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6361. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6362. var xScale = 2.0 / (leftTan + rightTan);
  6363. var yScale = 2.0 / (upTan + downTan);
  6364. result.m[0] = xScale;
  6365. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6366. result.m[5] = yScale;
  6367. result.m[6] = result.m[7] = 0.0;
  6368. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6369. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6370. result.m[10] = -zfar / (znear - zfar);
  6371. result.m[11] = 1.0 * rightHandedFactor;
  6372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6373. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6374. result._markAsUpdated();
  6375. };
  6376. /**
  6377. * Computes a complete transformation matrix
  6378. * @param viewport defines the viewport to use
  6379. * @param world defines the world matrix
  6380. * @param view defines the view matrix
  6381. * @param projection defines the projection matrix
  6382. * @param zmin defines the near clip plane
  6383. * @param zmax defines the far clip plane
  6384. * @returns the transformation matrix
  6385. */
  6386. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6387. var cw = viewport.width;
  6388. var ch = viewport.height;
  6389. var cx = viewport.x;
  6390. var cy = viewport.y;
  6391. 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);
  6392. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6393. };
  6394. /**
  6395. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6396. * @param matrix defines the matrix to use
  6397. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6398. */
  6399. Matrix.GetAsMatrix2x2 = function (matrix) {
  6400. return new Float32Array([
  6401. matrix.m[0], matrix.m[1],
  6402. matrix.m[4], matrix.m[5]
  6403. ]);
  6404. };
  6405. /**
  6406. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6407. * @param matrix defines the matrix to use
  6408. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6409. */
  6410. Matrix.GetAsMatrix3x3 = function (matrix) {
  6411. return new Float32Array([
  6412. matrix.m[0], matrix.m[1], matrix.m[2],
  6413. matrix.m[4], matrix.m[5], matrix.m[6],
  6414. matrix.m[8], matrix.m[9], matrix.m[10]
  6415. ]);
  6416. };
  6417. /**
  6418. * Compute the transpose of a given matrix
  6419. * @param matrix defines the matrix to transpose
  6420. * @returns the new matrix
  6421. */
  6422. Matrix.Transpose = function (matrix) {
  6423. var result = new Matrix();
  6424. Matrix.TransposeToRef(matrix, result);
  6425. return result;
  6426. };
  6427. /**
  6428. * Compute the transpose of a matrix and store it in a target matrix
  6429. * @param matrix defines the matrix to transpose
  6430. * @param result defines the target matrix
  6431. */
  6432. Matrix.TransposeToRef = function (matrix, result) {
  6433. result.m[0] = matrix.m[0];
  6434. result.m[1] = matrix.m[4];
  6435. result.m[2] = matrix.m[8];
  6436. result.m[3] = matrix.m[12];
  6437. result.m[4] = matrix.m[1];
  6438. result.m[5] = matrix.m[5];
  6439. result.m[6] = matrix.m[9];
  6440. result.m[7] = matrix.m[13];
  6441. result.m[8] = matrix.m[2];
  6442. result.m[9] = matrix.m[6];
  6443. result.m[10] = matrix.m[10];
  6444. result.m[11] = matrix.m[14];
  6445. result.m[12] = matrix.m[3];
  6446. result.m[13] = matrix.m[7];
  6447. result.m[14] = matrix.m[11];
  6448. result.m[15] = matrix.m[15];
  6449. };
  6450. /**
  6451. * Computes a reflection matrix from a plane
  6452. * @param plane defines the reflection plane
  6453. * @returns a new matrix
  6454. */
  6455. Matrix.Reflection = function (plane) {
  6456. var matrix = new Matrix();
  6457. Matrix.ReflectionToRef(plane, matrix);
  6458. return matrix;
  6459. };
  6460. /**
  6461. * Computes a reflection matrix from a plane
  6462. * @param plane defines the reflection plane
  6463. * @param result defines the target matrix
  6464. */
  6465. Matrix.ReflectionToRef = function (plane, result) {
  6466. plane.normalize();
  6467. var x = plane.normal.x;
  6468. var y = plane.normal.y;
  6469. var z = plane.normal.z;
  6470. var temp = -2 * x;
  6471. var temp2 = -2 * y;
  6472. var temp3 = -2 * z;
  6473. result.m[0] = (temp * x) + 1;
  6474. result.m[1] = temp2 * x;
  6475. result.m[2] = temp3 * x;
  6476. result.m[3] = 0.0;
  6477. result.m[4] = temp * y;
  6478. result.m[5] = (temp2 * y) + 1;
  6479. result.m[6] = temp3 * y;
  6480. result.m[7] = 0.0;
  6481. result.m[8] = temp * z;
  6482. result.m[9] = temp2 * z;
  6483. result.m[10] = (temp3 * z) + 1;
  6484. result.m[11] = 0.0;
  6485. result.m[12] = temp * plane.d;
  6486. result.m[13] = temp2 * plane.d;
  6487. result.m[14] = temp3 * plane.d;
  6488. result.m[15] = 1.0;
  6489. result._markAsUpdated();
  6490. };
  6491. /**
  6492. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6493. * @param xaxis defines the value of the 1st axis
  6494. * @param yaxis defines the value of the 2nd axis
  6495. * @param zaxis defines the value of the 3rd axis
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6499. result.m[0] = xaxis.x;
  6500. result.m[1] = xaxis.y;
  6501. result.m[2] = xaxis.z;
  6502. result.m[3] = 0.0;
  6503. result.m[4] = yaxis.x;
  6504. result.m[5] = yaxis.y;
  6505. result.m[6] = yaxis.z;
  6506. result.m[7] = 0.0;
  6507. result.m[8] = zaxis.x;
  6508. result.m[9] = zaxis.y;
  6509. result.m[10] = zaxis.z;
  6510. result.m[11] = 0.0;
  6511. result.m[12] = 0.0;
  6512. result.m[13] = 0.0;
  6513. result.m[14] = 0.0;
  6514. result.m[15] = 1.0;
  6515. result._markAsUpdated();
  6516. };
  6517. /**
  6518. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6519. * @param quat defines the quaternion to use
  6520. * @param result defines the target matrix
  6521. */
  6522. Matrix.FromQuaternionToRef = function (quat, result) {
  6523. var xx = quat.x * quat.x;
  6524. var yy = quat.y * quat.y;
  6525. var zz = quat.z * quat.z;
  6526. var xy = quat.x * quat.y;
  6527. var zw = quat.z * quat.w;
  6528. var zx = quat.z * quat.x;
  6529. var yw = quat.y * quat.w;
  6530. var yz = quat.y * quat.z;
  6531. var xw = quat.x * quat.w;
  6532. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6533. result.m[1] = 2.0 * (xy + zw);
  6534. result.m[2] = 2.0 * (zx - yw);
  6535. result.m[3] = 0.0;
  6536. result.m[4] = 2.0 * (xy - zw);
  6537. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6538. result.m[6] = 2.0 * (yz + xw);
  6539. result.m[7] = 0.0;
  6540. result.m[8] = 2.0 * (zx + yw);
  6541. result.m[9] = 2.0 * (yz - xw);
  6542. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6543. result.m[11] = 0.0;
  6544. result.m[12] = 0.0;
  6545. result.m[13] = 0.0;
  6546. result.m[14] = 0.0;
  6547. result.m[15] = 1.0;
  6548. result._markAsUpdated();
  6549. };
  6550. Matrix._tempQuaternion = new Quaternion();
  6551. Matrix._xAxis = Vector3.Zero();
  6552. Matrix._yAxis = Vector3.Zero();
  6553. Matrix._zAxis = Vector3.Zero();
  6554. Matrix._updateFlagSeed = 0;
  6555. Matrix._identityReadOnly = Matrix.Identity();
  6556. return Matrix;
  6557. }());
  6558. BABYLON.Matrix = Matrix;
  6559. var Plane = /** @class */ (function () {
  6560. /**
  6561. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6562. */
  6563. function Plane(a, b, c, d) {
  6564. this.normal = new Vector3(a, b, c);
  6565. this.d = d;
  6566. }
  6567. /**
  6568. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6569. */
  6570. Plane.prototype.asArray = function () {
  6571. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6572. };
  6573. // Methods
  6574. /**
  6575. * Returns a new plane copied from the current Plane.
  6576. */
  6577. Plane.prototype.clone = function () {
  6578. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6579. };
  6580. /**
  6581. * Returns the string "Plane".
  6582. */
  6583. Plane.prototype.getClassName = function () {
  6584. return "Plane";
  6585. };
  6586. /**
  6587. * Returns the Plane hash code.
  6588. */
  6589. Plane.prototype.getHashCode = function () {
  6590. var hash = this.normal.getHashCode();
  6591. hash = (hash * 397) ^ (this.d || 0);
  6592. return hash;
  6593. };
  6594. /**
  6595. * Normalize the current Plane in place.
  6596. * Returns the updated Plane.
  6597. */
  6598. Plane.prototype.normalize = function () {
  6599. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6600. var magnitude = 0.0;
  6601. if (norm !== 0) {
  6602. magnitude = 1.0 / norm;
  6603. }
  6604. this.normal.x *= magnitude;
  6605. this.normal.y *= magnitude;
  6606. this.normal.z *= magnitude;
  6607. this.d *= magnitude;
  6608. return this;
  6609. };
  6610. /**
  6611. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6612. */
  6613. Plane.prototype.transform = function (transformation) {
  6614. var transposedMatrix = Matrix.Transpose(transformation);
  6615. var x = this.normal.x;
  6616. var y = this.normal.y;
  6617. var z = this.normal.z;
  6618. var d = this.d;
  6619. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6620. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6621. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6622. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6623. return new Plane(normalX, normalY, normalZ, finalD);
  6624. };
  6625. /**
  6626. * Returns the dot product (float) of the point coordinates and the plane normal.
  6627. */
  6628. Plane.prototype.dotCoordinate = function (point) {
  6629. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6630. };
  6631. /**
  6632. * Updates the current Plane from the plane defined by the three given points.
  6633. * Returns the updated Plane.
  6634. */
  6635. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6636. var x1 = point2.x - point1.x;
  6637. var y1 = point2.y - point1.y;
  6638. var z1 = point2.z - point1.z;
  6639. var x2 = point3.x - point1.x;
  6640. var y2 = point3.y - point1.y;
  6641. var z2 = point3.z - point1.z;
  6642. var yz = (y1 * z2) - (z1 * y2);
  6643. var xz = (z1 * x2) - (x1 * z2);
  6644. var xy = (x1 * y2) - (y1 * x2);
  6645. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6646. var invPyth;
  6647. if (pyth !== 0) {
  6648. invPyth = 1.0 / pyth;
  6649. }
  6650. else {
  6651. invPyth = 0.0;
  6652. }
  6653. this.normal.x = yz * invPyth;
  6654. this.normal.y = xz * invPyth;
  6655. this.normal.z = xy * invPyth;
  6656. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6657. return this;
  6658. };
  6659. /**
  6660. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6661. */
  6662. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6663. var dot = Vector3.Dot(this.normal, direction);
  6664. return (dot <= epsilon);
  6665. };
  6666. /**
  6667. * Returns the signed distance (float) from the given point to the Plane.
  6668. */
  6669. Plane.prototype.signedDistanceTo = function (point) {
  6670. return Vector3.Dot(point, this.normal) + this.d;
  6671. };
  6672. // Statics
  6673. /**
  6674. * Returns a new Plane from the given array.
  6675. */
  6676. Plane.FromArray = function (array) {
  6677. return new Plane(array[0], array[1], array[2], array[3]);
  6678. };
  6679. /**
  6680. * Returns a new Plane defined by the three given points.
  6681. */
  6682. Plane.FromPoints = function (point1, point2, point3) {
  6683. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6684. result.copyFromPoints(point1, point2, point3);
  6685. return result;
  6686. };
  6687. /**
  6688. * Returns a new Plane the normal vector to this plane at the given origin point.
  6689. * Note : the vector "normal" is updated because normalized.
  6690. */
  6691. Plane.FromPositionAndNormal = function (origin, normal) {
  6692. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6693. normal.normalize();
  6694. result.normal = normal;
  6695. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6696. return result;
  6697. };
  6698. /**
  6699. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6700. */
  6701. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6702. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6703. return Vector3.Dot(point, normal) + d;
  6704. };
  6705. return Plane;
  6706. }());
  6707. BABYLON.Plane = Plane;
  6708. var Viewport = /** @class */ (function () {
  6709. /**
  6710. * Creates a Viewport object located at (x, y) and sized (width, height).
  6711. */
  6712. function Viewport(x, y, width, height) {
  6713. this.x = x;
  6714. this.y = y;
  6715. this.width = width;
  6716. this.height = height;
  6717. }
  6718. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6719. if (renderWidthOrEngine.getRenderWidth) {
  6720. var engine = renderWidthOrEngine;
  6721. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6722. }
  6723. var renderWidth = renderWidthOrEngine;
  6724. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6725. };
  6726. /**
  6727. * Returns a new Viewport copied from the current one.
  6728. */
  6729. Viewport.prototype.clone = function () {
  6730. return new Viewport(this.x, this.y, this.width, this.height);
  6731. };
  6732. return Viewport;
  6733. }());
  6734. BABYLON.Viewport = Viewport;
  6735. var Frustum = /** @class */ (function () {
  6736. function Frustum() {
  6737. }
  6738. /**
  6739. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6740. */
  6741. Frustum.GetPlanes = function (transform) {
  6742. var frustumPlanes = [];
  6743. for (var index = 0; index < 6; index++) {
  6744. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6745. }
  6746. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6747. return frustumPlanes;
  6748. };
  6749. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6750. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6751. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6752. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6753. frustumPlane.d = transform.m[15] + transform.m[14];
  6754. frustumPlane.normalize();
  6755. };
  6756. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6757. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6758. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6759. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6760. frustumPlane.d = transform.m[15] - transform.m[14];
  6761. frustumPlane.normalize();
  6762. };
  6763. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6764. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6765. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6766. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6767. frustumPlane.d = transform.m[15] + transform.m[12];
  6768. frustumPlane.normalize();
  6769. };
  6770. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6771. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6772. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6773. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6774. frustumPlane.d = transform.m[15] - transform.m[12];
  6775. frustumPlane.normalize();
  6776. };
  6777. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6778. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6779. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6780. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6781. frustumPlane.d = transform.m[15] - transform.m[13];
  6782. frustumPlane.normalize();
  6783. };
  6784. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6785. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6786. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6787. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6788. frustumPlane.d = transform.m[15] + transform.m[13];
  6789. frustumPlane.normalize();
  6790. };
  6791. /**
  6792. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6793. */
  6794. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6795. // Near
  6796. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6797. // Far
  6798. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6799. // Left
  6800. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6801. // Right
  6802. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6803. // Top
  6804. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6805. // Bottom
  6806. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6807. };
  6808. return Frustum;
  6809. }());
  6810. BABYLON.Frustum = Frustum;
  6811. /** Defines supported spaces */
  6812. var Space;
  6813. (function (Space) {
  6814. /** Local (object) space */
  6815. Space[Space["LOCAL"] = 0] = "LOCAL";
  6816. /** World space */
  6817. Space[Space["WORLD"] = 1] = "WORLD";
  6818. /** Bone space */
  6819. Space[Space["BONE"] = 2] = "BONE";
  6820. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6821. /** Defines the 3 main axes */
  6822. var Axis = /** @class */ (function () {
  6823. function Axis() {
  6824. }
  6825. /** X axis */
  6826. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6827. /** Y axis */
  6828. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6829. /** Z axis */
  6830. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6831. return Axis;
  6832. }());
  6833. BABYLON.Axis = Axis;
  6834. ;
  6835. var BezierCurve = /** @class */ (function () {
  6836. function BezierCurve() {
  6837. }
  6838. /**
  6839. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6840. */
  6841. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6842. // Extract X (which is equal to time here)
  6843. var f0 = 1 - 3 * x2 + 3 * x1;
  6844. var f1 = 3 * x2 - 6 * x1;
  6845. var f2 = 3 * x1;
  6846. var refinedT = t;
  6847. for (var i = 0; i < 5; i++) {
  6848. var refinedT2 = refinedT * refinedT;
  6849. var refinedT3 = refinedT2 * refinedT;
  6850. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6851. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6852. refinedT -= (x - t) * slope;
  6853. refinedT = Math.min(1, Math.max(0, refinedT));
  6854. }
  6855. // Resolve cubic bezier for the given x
  6856. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6857. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6858. Math.pow(refinedT, 3);
  6859. };
  6860. return BezierCurve;
  6861. }());
  6862. BABYLON.BezierCurve = BezierCurve;
  6863. /**
  6864. * Defines potential orientation for back face culling
  6865. */
  6866. var Orientation;
  6867. (function (Orientation) {
  6868. /**
  6869. * Clockwise
  6870. */
  6871. Orientation[Orientation["CW"] = 0] = "CW";
  6872. /** Counter clockwise */
  6873. Orientation[Orientation["CCW"] = 1] = "CCW";
  6874. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6875. /**
  6876. * Defines angle representation
  6877. */
  6878. var Angle = /** @class */ (function () {
  6879. /**
  6880. * Creates an Angle object of "radians" radians (float).
  6881. */
  6882. function Angle(radians) {
  6883. this._radians = radians;
  6884. if (this._radians < 0.0)
  6885. this._radians += (2.0 * Math.PI);
  6886. }
  6887. /**
  6888. * Get value in degrees
  6889. * @returns the Angle value in degrees (float)
  6890. */
  6891. Angle.prototype.degrees = function () {
  6892. return this._radians * 180.0 / Math.PI;
  6893. };
  6894. /**
  6895. * Get value in radians
  6896. * @returns the Angle value in radians (float)
  6897. */
  6898. Angle.prototype.radians = function () {
  6899. return this._radians;
  6900. };
  6901. /**
  6902. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6903. * @param a defines first vector
  6904. * @param b defines second vector
  6905. * @returns a new Angle
  6906. */
  6907. Angle.BetweenTwoPoints = function (a, b) {
  6908. var delta = b.subtract(a);
  6909. var theta = Math.atan2(delta.y, delta.x);
  6910. return new Angle(theta);
  6911. };
  6912. /**
  6913. * Gets a new Angle object from the given float in radians
  6914. * @param radians defines the angle value in radians
  6915. * @returns a new Angle
  6916. */
  6917. Angle.FromRadians = function (radians) {
  6918. return new Angle(radians);
  6919. };
  6920. /**
  6921. * Gets a new Angle object from the given float in degrees
  6922. * @param degrees defines the angle value in degrees
  6923. * @returns a new Angle
  6924. */
  6925. Angle.FromDegrees = function (degrees) {
  6926. return new Angle(degrees * Math.PI / 180.0);
  6927. };
  6928. return Angle;
  6929. }());
  6930. BABYLON.Angle = Angle;
  6931. var Arc2 = /** @class */ (function () {
  6932. /**
  6933. * Creates an Arc object from the three given points : start, middle and end.
  6934. */
  6935. function Arc2(startPoint, midPoint, endPoint) {
  6936. this.startPoint = startPoint;
  6937. this.midPoint = midPoint;
  6938. this.endPoint = endPoint;
  6939. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6940. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6941. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6942. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6943. 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);
  6944. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6945. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6946. var a1 = this.startAngle.degrees();
  6947. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6948. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6949. // angles correction
  6950. if (a2 - a1 > +180.0)
  6951. a2 -= 360.0;
  6952. if (a2 - a1 < -180.0)
  6953. a2 += 360.0;
  6954. if (a3 - a2 > +180.0)
  6955. a3 -= 360.0;
  6956. if (a3 - a2 < -180.0)
  6957. a3 += 360.0;
  6958. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6959. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6960. }
  6961. return Arc2;
  6962. }());
  6963. BABYLON.Arc2 = Arc2;
  6964. var Path2 = /** @class */ (function () {
  6965. /**
  6966. * Creates a Path2 object from the starting 2D coordinates x and y.
  6967. */
  6968. function Path2(x, y) {
  6969. this._points = new Array();
  6970. this._length = 0.0;
  6971. this.closed = false;
  6972. this._points.push(new Vector2(x, y));
  6973. }
  6974. /**
  6975. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6976. * Returns the updated Path2.
  6977. */
  6978. Path2.prototype.addLineTo = function (x, y) {
  6979. if (this.closed) {
  6980. return this;
  6981. }
  6982. var newPoint = new Vector2(x, y);
  6983. var previousPoint = this._points[this._points.length - 1];
  6984. this._points.push(newPoint);
  6985. this._length += newPoint.subtract(previousPoint).length();
  6986. return this;
  6987. };
  6988. /**
  6989. * 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.
  6990. * Returns the updated Path2.
  6991. */
  6992. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6993. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6994. if (this.closed) {
  6995. return this;
  6996. }
  6997. var startPoint = this._points[this._points.length - 1];
  6998. var midPoint = new Vector2(midX, midY);
  6999. var endPoint = new Vector2(endX, endY);
  7000. var arc = new Arc2(startPoint, midPoint, endPoint);
  7001. var increment = arc.angle.radians() / numberOfSegments;
  7002. if (arc.orientation === Orientation.CW)
  7003. increment *= -1;
  7004. var currentAngle = arc.startAngle.radians() + increment;
  7005. for (var i = 0; i < numberOfSegments; i++) {
  7006. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7007. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7008. this.addLineTo(x, y);
  7009. currentAngle += increment;
  7010. }
  7011. return this;
  7012. };
  7013. /**
  7014. * Closes the Path2.
  7015. * Returns the Path2.
  7016. */
  7017. Path2.prototype.close = function () {
  7018. this.closed = true;
  7019. return this;
  7020. };
  7021. /**
  7022. * Returns the Path2 total length (float).
  7023. */
  7024. Path2.prototype.length = function () {
  7025. var result = this._length;
  7026. if (!this.closed) {
  7027. var lastPoint = this._points[this._points.length - 1];
  7028. var firstPoint = this._points[0];
  7029. result += (firstPoint.subtract(lastPoint).length());
  7030. }
  7031. return result;
  7032. };
  7033. /**
  7034. * Returns the Path2 internal array of points.
  7035. */
  7036. Path2.prototype.getPoints = function () {
  7037. return this._points;
  7038. };
  7039. /**
  7040. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7041. */
  7042. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7043. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7044. return Vector2.Zero();
  7045. }
  7046. var lengthPosition = normalizedLengthPosition * this.length();
  7047. var previousOffset = 0;
  7048. for (var i = 0; i < this._points.length; i++) {
  7049. var j = (i + 1) % this._points.length;
  7050. var a = this._points[i];
  7051. var b = this._points[j];
  7052. var bToA = b.subtract(a);
  7053. var nextOffset = (bToA.length() + previousOffset);
  7054. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7055. var dir = bToA.normalize();
  7056. var localOffset = lengthPosition - previousOffset;
  7057. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7058. }
  7059. previousOffset = nextOffset;
  7060. }
  7061. return Vector2.Zero();
  7062. };
  7063. /**
  7064. * Returns a new Path2 starting at the coordinates (x, y).
  7065. */
  7066. Path2.StartingAt = function (x, y) {
  7067. return new Path2(x, y);
  7068. };
  7069. return Path2;
  7070. }());
  7071. BABYLON.Path2 = Path2;
  7072. var Path3D = /** @class */ (function () {
  7073. /**
  7074. * new Path3D(path, normal, raw)
  7075. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7076. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7077. * path : an array of Vector3, the curve axis of the Path3D
  7078. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7079. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7080. */
  7081. function Path3D(path, firstNormal, raw) {
  7082. if (firstNormal === void 0) { firstNormal = null; }
  7083. this.path = path;
  7084. this._curve = new Array();
  7085. this._distances = new Array();
  7086. this._tangents = new Array();
  7087. this._normals = new Array();
  7088. this._binormals = new Array();
  7089. for (var p = 0; p < path.length; p++) {
  7090. this._curve[p] = path[p].clone(); // hard copy
  7091. }
  7092. this._raw = raw || false;
  7093. this._compute(firstNormal);
  7094. }
  7095. /**
  7096. * Returns the Path3D array of successive Vector3 designing its curve.
  7097. */
  7098. Path3D.prototype.getCurve = function () {
  7099. return this._curve;
  7100. };
  7101. /**
  7102. * Returns an array populated with tangent vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getTangents = function () {
  7105. return this._tangents;
  7106. };
  7107. /**
  7108. * Returns an array populated with normal vectors on each Path3D curve point.
  7109. */
  7110. Path3D.prototype.getNormals = function () {
  7111. return this._normals;
  7112. };
  7113. /**
  7114. * Returns an array populated with binormal vectors on each Path3D curve point.
  7115. */
  7116. Path3D.prototype.getBinormals = function () {
  7117. return this._binormals;
  7118. };
  7119. /**
  7120. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7121. */
  7122. Path3D.prototype.getDistances = function () {
  7123. return this._distances;
  7124. };
  7125. /**
  7126. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7127. * Returns the same object updated.
  7128. */
  7129. Path3D.prototype.update = function (path, firstNormal) {
  7130. if (firstNormal === void 0) { firstNormal = null; }
  7131. for (var p = 0; p < path.length; p++) {
  7132. this._curve[p].x = path[p].x;
  7133. this._curve[p].y = path[p].y;
  7134. this._curve[p].z = path[p].z;
  7135. }
  7136. this._compute(firstNormal);
  7137. return this;
  7138. };
  7139. // private function compute() : computes tangents, normals and binormals
  7140. Path3D.prototype._compute = function (firstNormal) {
  7141. var l = this._curve.length;
  7142. // first and last tangents
  7143. this._tangents[0] = this._getFirstNonNullVector(0);
  7144. if (!this._raw) {
  7145. this._tangents[0].normalize();
  7146. }
  7147. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7148. if (!this._raw) {
  7149. this._tangents[l - 1].normalize();
  7150. }
  7151. // normals and binormals at first point : arbitrary vector with _normalVector()
  7152. var tg0 = this._tangents[0];
  7153. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7154. this._normals[0] = pp0;
  7155. if (!this._raw) {
  7156. this._normals[0].normalize();
  7157. }
  7158. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7159. if (!this._raw) {
  7160. this._binormals[0].normalize();
  7161. }
  7162. this._distances[0] = 0.0;
  7163. // normals and binormals : next points
  7164. var prev; // previous vector (segment)
  7165. var cur; // current vector (segment)
  7166. var curTang; // current tangent
  7167. // previous normal
  7168. var prevBinor; // previous binormal
  7169. for (var i = 1; i < l; i++) {
  7170. // tangents
  7171. prev = this._getLastNonNullVector(i);
  7172. if (i < l - 1) {
  7173. cur = this._getFirstNonNullVector(i);
  7174. this._tangents[i] = prev.add(cur);
  7175. this._tangents[i].normalize();
  7176. }
  7177. this._distances[i] = this._distances[i - 1] + prev.length();
  7178. // normals and binormals
  7179. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7180. curTang = this._tangents[i];
  7181. prevBinor = this._binormals[i - 1];
  7182. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7183. if (!this._raw) {
  7184. this._normals[i].normalize();
  7185. }
  7186. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7187. if (!this._raw) {
  7188. this._binormals[i].normalize();
  7189. }
  7190. }
  7191. };
  7192. // private function getFirstNonNullVector(index)
  7193. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7194. Path3D.prototype._getFirstNonNullVector = function (index) {
  7195. var i = 1;
  7196. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7197. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7198. i++;
  7199. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7200. }
  7201. return nNVector;
  7202. };
  7203. // private function getLastNonNullVector(index)
  7204. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7205. Path3D.prototype._getLastNonNullVector = function (index) {
  7206. var i = 1;
  7207. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7208. while (nLVector.length() === 0 && index > i + 1) {
  7209. i++;
  7210. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7211. }
  7212. return nLVector;
  7213. };
  7214. // private function normalVector(v0, vt, va) :
  7215. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7216. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7217. Path3D.prototype._normalVector = function (v0, vt, va) {
  7218. var normal0;
  7219. var tgl = vt.length();
  7220. if (tgl === 0.0) {
  7221. tgl = 1.0;
  7222. }
  7223. if (va === undefined || va === null) {
  7224. var point;
  7225. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7226. point = new Vector3(0.0, -1.0, 0.0);
  7227. }
  7228. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7229. point = new Vector3(1.0, 0.0, 0.0);
  7230. }
  7231. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7232. point = new Vector3(0.0, 0.0, 1.0);
  7233. }
  7234. else {
  7235. point = Vector3.Zero();
  7236. }
  7237. normal0 = Vector3.Cross(vt, point);
  7238. }
  7239. else {
  7240. normal0 = Vector3.Cross(vt, va);
  7241. Vector3.CrossToRef(normal0, vt, normal0);
  7242. }
  7243. normal0.normalize();
  7244. return normal0;
  7245. };
  7246. return Path3D;
  7247. }());
  7248. BABYLON.Path3D = Path3D;
  7249. var Curve3 = /** @class */ (function () {
  7250. /**
  7251. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7252. * A Curve3 is designed from a series of successive Vector3.
  7253. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7254. */
  7255. function Curve3(points) {
  7256. this._length = 0.0;
  7257. this._points = points;
  7258. this._length = this._computeLength(points);
  7259. }
  7260. /**
  7261. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7262. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7263. * @param v1 (Vector3) the control point
  7264. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7265. * @param nbPoints (integer) the wanted number of points in the curve
  7266. */
  7267. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7268. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7269. var bez = new Array();
  7270. var equation = function (t, val0, val1, val2) {
  7271. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7272. return res;
  7273. };
  7274. for (var i = 0; i <= nbPoints; i++) {
  7275. 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)));
  7276. }
  7277. return new Curve3(bez);
  7278. };
  7279. /**
  7280. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7281. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7282. * @param v1 (Vector3) the first control point
  7283. * @param v2 (Vector3) the second control point
  7284. * @param v3 (Vector3) the end point of the Cubic Bezier
  7285. * @param nbPoints (integer) the wanted number of points in the curve
  7286. */
  7287. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7288. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7289. var bez = new Array();
  7290. var equation = function (t, val0, val1, val2, val3) {
  7291. 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;
  7292. return res;
  7293. };
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. 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)));
  7296. }
  7297. return new Curve3(bez);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7301. * @param p1 (Vector3) the origin point of the Hermite Spline
  7302. * @param t1 (Vector3) the tangent vector at the origin point
  7303. * @param p2 (Vector3) the end point of the Hermite Spline
  7304. * @param t2 (Vector3) the tangent vector at the end point
  7305. * @param nbPoints (integer) the wanted number of points in the curve
  7306. */
  7307. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7308. var hermite = new Array();
  7309. var step = 1.0 / nbPoints;
  7310. for (var i = 0; i <= nbPoints; i++) {
  7311. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7312. }
  7313. return new Curve3(hermite);
  7314. };
  7315. /**
  7316. * Returns a Curve3 object along a CatmullRom Spline curve :
  7317. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7318. * @param nbPoints (integer) the wanted number of points between each curve control points
  7319. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7320. */
  7321. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7322. var catmullRom = new Array();
  7323. var step = 1.0 / nbPoints;
  7324. var amount = 0.0;
  7325. if (closed) {
  7326. var pointsCount = points.length;
  7327. for (var i = 0; i < pointsCount; i++) {
  7328. amount = 0;
  7329. for (var c = 0; c < nbPoints; c++) {
  7330. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7331. amount += step;
  7332. }
  7333. }
  7334. catmullRom.push(catmullRom[0]);
  7335. }
  7336. else {
  7337. var totalPoints = new Array();
  7338. totalPoints.push(points[0].clone());
  7339. Array.prototype.push.apply(totalPoints, points);
  7340. totalPoints.push(points[points.length - 1].clone());
  7341. for (var i = 0; i < totalPoints.length - 3; i++) {
  7342. amount = 0;
  7343. for (var c = 0; c < nbPoints; c++) {
  7344. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7345. amount += step;
  7346. }
  7347. }
  7348. i--;
  7349. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7350. }
  7351. return new Curve3(catmullRom);
  7352. };
  7353. /**
  7354. * Returns the Curve3 stored array of successive Vector3
  7355. */
  7356. Curve3.prototype.getPoints = function () {
  7357. return this._points;
  7358. };
  7359. /**
  7360. * Returns the computed length (float) of the curve.
  7361. */
  7362. Curve3.prototype.length = function () {
  7363. return this._length;
  7364. };
  7365. /**
  7366. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7367. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7368. * curveA and curveB keep unchanged.
  7369. */
  7370. Curve3.prototype.continue = function (curve) {
  7371. var lastPoint = this._points[this._points.length - 1];
  7372. var continuedPoints = this._points.slice();
  7373. var curvePoints = curve.getPoints();
  7374. for (var i = 1; i < curvePoints.length; i++) {
  7375. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7376. }
  7377. var continuedCurve = new Curve3(continuedPoints);
  7378. return continuedCurve;
  7379. };
  7380. Curve3.prototype._computeLength = function (path) {
  7381. var l = 0;
  7382. for (var i = 1; i < path.length; i++) {
  7383. l += (path[i].subtract(path[i - 1])).length();
  7384. }
  7385. return l;
  7386. };
  7387. return Curve3;
  7388. }());
  7389. BABYLON.Curve3 = Curve3;
  7390. // Vertex formats
  7391. var PositionNormalVertex = /** @class */ (function () {
  7392. function PositionNormalVertex(position, normal) {
  7393. if (position === void 0) { position = Vector3.Zero(); }
  7394. if (normal === void 0) { normal = Vector3.Up(); }
  7395. this.position = position;
  7396. this.normal = normal;
  7397. }
  7398. PositionNormalVertex.prototype.clone = function () {
  7399. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7400. };
  7401. return PositionNormalVertex;
  7402. }());
  7403. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7404. var PositionNormalTextureVertex = /** @class */ (function () {
  7405. function PositionNormalTextureVertex(position, normal, uv) {
  7406. if (position === void 0) { position = Vector3.Zero(); }
  7407. if (normal === void 0) { normal = Vector3.Up(); }
  7408. if (uv === void 0) { uv = Vector2.Zero(); }
  7409. this.position = position;
  7410. this.normal = normal;
  7411. this.uv = uv;
  7412. }
  7413. PositionNormalTextureVertex.prototype.clone = function () {
  7414. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7415. };
  7416. return PositionNormalTextureVertex;
  7417. }());
  7418. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7419. // Temporary pre-allocated objects for engine internal use
  7420. // usage in any internal function :
  7421. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7422. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7423. var Tmp = /** @class */ (function () {
  7424. function Tmp() {
  7425. }
  7426. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7427. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7428. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7429. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7430. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7431. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7432. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7433. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7434. Matrix.Zero(), Matrix.Zero(),
  7435. Matrix.Zero(), Matrix.Zero(),
  7436. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7437. return Tmp;
  7438. }());
  7439. BABYLON.Tmp = Tmp;
  7440. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7441. var MathTmp = /** @class */ (function () {
  7442. function MathTmp() {
  7443. }
  7444. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7445. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7446. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7447. return MathTmp;
  7448. }());
  7449. })(BABYLON || (BABYLON = {}));
  7450. //# sourceMappingURL=babylon.math.js.map
  7451. var BABYLON;
  7452. (function (BABYLON) {
  7453. var Scalar = /** @class */ (function () {
  7454. function Scalar() {
  7455. }
  7456. /**
  7457. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7458. */
  7459. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7460. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7461. var num = a - b;
  7462. return -epsilon <= num && num <= epsilon;
  7463. };
  7464. /**
  7465. * Returns a string : the upper case translation of the number i to hexadecimal.
  7466. */
  7467. Scalar.ToHex = function (i) {
  7468. var str = i.toString(16);
  7469. if (i <= 15) {
  7470. return ("0" + str).toUpperCase();
  7471. }
  7472. return str.toUpperCase();
  7473. };
  7474. /**
  7475. * Returns -1 if value is negative and +1 is value is positive.
  7476. * Returns the value itself if it's equal to zero.
  7477. */
  7478. Scalar.Sign = function (value) {
  7479. value = +value; // convert to a number
  7480. if (value === 0 || isNaN(value))
  7481. return value;
  7482. return value > 0 ? 1 : -1;
  7483. };
  7484. /**
  7485. * Returns the value itself if it's between min and max.
  7486. * Returns min if the value is lower than min.
  7487. * Returns max if the value is greater than max.
  7488. */
  7489. Scalar.Clamp = function (value, min, max) {
  7490. if (min === void 0) { min = 0; }
  7491. if (max === void 0) { max = 1; }
  7492. return Math.min(max, Math.max(min, value));
  7493. };
  7494. /**
  7495. * Returns the log2 of value.
  7496. */
  7497. Scalar.Log2 = function (value) {
  7498. return Math.log(value) * Math.LOG2E;
  7499. };
  7500. /**
  7501. * Loops the value, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * This is similar to the modulo operator but it works with floating point numbers.
  7504. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7505. * With t = 5 and length = 2.5, the result would be 0.0.
  7506. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7507. */
  7508. Scalar.Repeat = function (value, length) {
  7509. return value - Math.floor(value / length) * length;
  7510. };
  7511. /**
  7512. * Normalize the value between 0.0 and 1.0 using min and max values
  7513. */
  7514. Scalar.Normalize = function (value, min, max) {
  7515. return (value - min) / (max - min);
  7516. };
  7517. /**
  7518. * Denormalize the value from 0.0 and 1.0 using min and max values
  7519. */
  7520. Scalar.Denormalize = function (normalized, min, max) {
  7521. return (normalized * (max - min) + min);
  7522. };
  7523. /**
  7524. * Calculates the shortest difference between two given angles given in degrees.
  7525. */
  7526. Scalar.DeltaAngle = function (current, target) {
  7527. var num = Scalar.Repeat(target - current, 360.0);
  7528. if (num > 180.0) {
  7529. num -= 360.0;
  7530. }
  7531. return num;
  7532. };
  7533. /**
  7534. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7535. *
  7536. * The returned value will move back and forth between 0 and length
  7537. */
  7538. Scalar.PingPong = function (tx, length) {
  7539. var t = Scalar.Repeat(tx, length * 2.0);
  7540. return length - Math.abs(t - length);
  7541. };
  7542. /**
  7543. * Interpolates between min and max with smoothing at the limits.
  7544. *
  7545. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7546. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7547. */
  7548. Scalar.SmoothStep = function (from, to, tx) {
  7549. var t = Scalar.Clamp(tx);
  7550. t = -2.0 * t * t * t + 3.0 * t * t;
  7551. return to * t + from * (1.0 - t);
  7552. };
  7553. /**
  7554. * Moves a value current towards target.
  7555. *
  7556. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7557. * Negative values of maxDelta pushes the value away from target.
  7558. */
  7559. Scalar.MoveTowards = function (current, target, maxDelta) {
  7560. var result = 0;
  7561. if (Math.abs(target - current) <= maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. result = current + Scalar.Sign(target - current) * maxDelta;
  7566. }
  7567. return result;
  7568. };
  7569. /**
  7570. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7571. *
  7572. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7573. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7574. */
  7575. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7576. var num = Scalar.DeltaAngle(current, target);
  7577. var result = 0;
  7578. if (-maxDelta < num && num < maxDelta) {
  7579. result = target;
  7580. }
  7581. else {
  7582. target = current + num;
  7583. result = Scalar.MoveTowards(current, target, maxDelta);
  7584. }
  7585. return result;
  7586. };
  7587. /**
  7588. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7589. */
  7590. Scalar.Lerp = function (start, end, amount) {
  7591. return start + ((end - start) * amount);
  7592. };
  7593. /**
  7594. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7595. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7596. */
  7597. Scalar.LerpAngle = function (start, end, amount) {
  7598. var num = Scalar.Repeat(end - start, 360.0);
  7599. if (num > 180.0) {
  7600. num -= 360.0;
  7601. }
  7602. return start + num * Scalar.Clamp(amount);
  7603. };
  7604. /**
  7605. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7606. */
  7607. Scalar.InverseLerp = function (a, b, value) {
  7608. var result = 0;
  7609. if (a != b) {
  7610. result = Scalar.Clamp((value - a) / (b - a));
  7611. }
  7612. else {
  7613. result = 0.0;
  7614. }
  7615. return result;
  7616. };
  7617. /**
  7618. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7619. */
  7620. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7621. var squared = amount * amount;
  7622. var cubed = amount * squared;
  7623. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7624. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7625. var part3 = (cubed - (2.0 * squared)) + amount;
  7626. var part4 = cubed - squared;
  7627. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7628. };
  7629. /**
  7630. * Returns a random float number between and min and max values
  7631. */
  7632. Scalar.RandomRange = function (min, max) {
  7633. if (min === max)
  7634. return min;
  7635. return ((Math.random() * (max - min)) + min);
  7636. };
  7637. /**
  7638. * This function returns percentage of a number in a given range.
  7639. *
  7640. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7641. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7642. */
  7643. Scalar.RangeToPercent = function (number, min, max) {
  7644. return ((number - min) / (max - min));
  7645. };
  7646. /**
  7647. * This function returns number that corresponds to the percentage in a given range.
  7648. *
  7649. * PercentToRange(0.34,0,100) will return 34.
  7650. */
  7651. Scalar.PercentToRange = function (percent, min, max) {
  7652. return ((max - min) * percent + min);
  7653. };
  7654. /**
  7655. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7656. * @param angle The angle to normalize in radian.
  7657. * @return The converted angle.
  7658. */
  7659. Scalar.NormalizeRadians = function (angle) {
  7660. // More precise but slower version kept for reference.
  7661. // angle = angle % Tools.TwoPi;
  7662. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7663. //if (angle > Math.PI) {
  7664. // angle -= Tools.TwoPi;
  7665. //}
  7666. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7667. return angle;
  7668. };
  7669. /**
  7670. * Two pi constants convenient for computation.
  7671. */
  7672. Scalar.TwoPi = Math.PI * 2;
  7673. return Scalar;
  7674. }());
  7675. BABYLON.Scalar = Scalar;
  7676. })(BABYLON || (BABYLON = {}));
  7677. //# sourceMappingURL=babylon.math.scalar.js.map
  7678. //# sourceMappingURL=babylon.mixins.js.map
  7679. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7680. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7681. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7682. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7683. //# sourceMappingURL=babylon.webgl2.js.map
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var __decoratorInitialStore = {};
  7687. var __mergedStore = {};
  7688. var _copySource = function (creationFunction, source, instanciate) {
  7689. var destination = creationFunction();
  7690. // Tags
  7691. if (BABYLON.Tags) {
  7692. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7693. }
  7694. var classStore = getMergedStore(destination);
  7695. // Properties
  7696. for (var property in classStore) {
  7697. var propertyDescriptor = classStore[property];
  7698. var sourceProperty = source[property];
  7699. var propertyType = propertyDescriptor.type;
  7700. if (sourceProperty !== undefined && sourceProperty !== null) {
  7701. switch (propertyType) {
  7702. case 0: // Value
  7703. case 6: // Mesh reference
  7704. case 11: // Camera reference
  7705. destination[property] = sourceProperty;
  7706. break;
  7707. case 1: // Texture
  7708. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7709. break;
  7710. case 2: // Color3
  7711. case 3: // FresnelParameters
  7712. case 4: // Vector2
  7713. case 5: // Vector3
  7714. case 7: // Color Curves
  7715. case 10: // Quaternion
  7716. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7717. break;
  7718. }
  7719. }
  7720. }
  7721. return destination;
  7722. };
  7723. function getDirectStore(target) {
  7724. var classKey = target.getClassName();
  7725. if (!__decoratorInitialStore[classKey]) {
  7726. __decoratorInitialStore[classKey] = {};
  7727. }
  7728. return __decoratorInitialStore[classKey];
  7729. }
  7730. /**
  7731. * Return the list of properties flagged as serializable
  7732. * @param target: host object
  7733. */
  7734. function getMergedStore(target) {
  7735. var classKey = target.getClassName();
  7736. if (__mergedStore[classKey]) {
  7737. return __mergedStore[classKey];
  7738. }
  7739. __mergedStore[classKey] = {};
  7740. var store = __mergedStore[classKey];
  7741. var currentTarget = target;
  7742. var currentKey = classKey;
  7743. while (currentKey) {
  7744. var initialStore = __decoratorInitialStore[currentKey];
  7745. for (var property in initialStore) {
  7746. store[property] = initialStore[property];
  7747. }
  7748. var parent_1 = void 0;
  7749. var done = false;
  7750. do {
  7751. parent_1 = Object.getPrototypeOf(currentTarget);
  7752. if (!parent_1.getClassName) {
  7753. done = true;
  7754. break;
  7755. }
  7756. if (parent_1.getClassName() !== currentKey) {
  7757. break;
  7758. }
  7759. currentTarget = parent_1;
  7760. } while (parent_1);
  7761. if (done) {
  7762. break;
  7763. }
  7764. currentKey = parent_1.getClassName();
  7765. currentTarget = parent_1;
  7766. }
  7767. return store;
  7768. }
  7769. function generateSerializableMember(type, sourceName) {
  7770. return function (target, propertyKey) {
  7771. var classStore = getDirectStore(target);
  7772. if (!classStore[propertyKey]) {
  7773. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7774. }
  7775. };
  7776. }
  7777. function generateExpandMember(setCallback, targetKey) {
  7778. if (targetKey === void 0) { targetKey = null; }
  7779. return function (target, propertyKey) {
  7780. var key = targetKey || ("_" + propertyKey);
  7781. Object.defineProperty(target, propertyKey, {
  7782. get: function () {
  7783. return this[key];
  7784. },
  7785. set: function (value) {
  7786. if (this[key] === value) {
  7787. return;
  7788. }
  7789. this[key] = value;
  7790. target[setCallback].apply(this);
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. };
  7796. }
  7797. function expandToProperty(callback, targetKey) {
  7798. if (targetKey === void 0) { targetKey = null; }
  7799. return generateExpandMember(callback, targetKey);
  7800. }
  7801. BABYLON.expandToProperty = expandToProperty;
  7802. function serialize(sourceName) {
  7803. return generateSerializableMember(0, sourceName); // value member
  7804. }
  7805. BABYLON.serialize = serialize;
  7806. function serializeAsTexture(sourceName) {
  7807. return generateSerializableMember(1, sourceName); // texture member
  7808. }
  7809. BABYLON.serializeAsTexture = serializeAsTexture;
  7810. function serializeAsColor3(sourceName) {
  7811. return generateSerializableMember(2, sourceName); // color3 member
  7812. }
  7813. BABYLON.serializeAsColor3 = serializeAsColor3;
  7814. function serializeAsFresnelParameters(sourceName) {
  7815. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7816. }
  7817. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7818. function serializeAsVector2(sourceName) {
  7819. return generateSerializableMember(4, sourceName); // vector2 member
  7820. }
  7821. BABYLON.serializeAsVector2 = serializeAsVector2;
  7822. function serializeAsVector3(sourceName) {
  7823. return generateSerializableMember(5, sourceName); // vector3 member
  7824. }
  7825. BABYLON.serializeAsVector3 = serializeAsVector3;
  7826. function serializeAsMeshReference(sourceName) {
  7827. return generateSerializableMember(6, sourceName); // mesh reference member
  7828. }
  7829. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7830. function serializeAsColorCurves(sourceName) {
  7831. return generateSerializableMember(7, sourceName); // color curves
  7832. }
  7833. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7834. function serializeAsColor4(sourceName) {
  7835. return generateSerializableMember(8, sourceName); // color 4
  7836. }
  7837. BABYLON.serializeAsColor4 = serializeAsColor4;
  7838. function serializeAsImageProcessingConfiguration(sourceName) {
  7839. return generateSerializableMember(9, sourceName); // image processing
  7840. }
  7841. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7842. function serializeAsQuaternion(sourceName) {
  7843. return generateSerializableMember(10, sourceName); // quaternion member
  7844. }
  7845. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7846. /**
  7847. * Decorator used to define property that can be serialized as reference to a camera
  7848. * @param sourceName defines the name of the property to decorate
  7849. */
  7850. function serializeAsCameraReference(sourceName) {
  7851. return generateSerializableMember(11, sourceName); // camera reference member
  7852. }
  7853. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7854. var SerializationHelper = /** @class */ (function () {
  7855. function SerializationHelper() {
  7856. }
  7857. SerializationHelper.Serialize = function (entity, serializationObject) {
  7858. if (!serializationObject) {
  7859. serializationObject = {};
  7860. }
  7861. // Tags
  7862. if (BABYLON.Tags) {
  7863. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7864. }
  7865. var serializedProperties = getMergedStore(entity);
  7866. // Properties
  7867. for (var property in serializedProperties) {
  7868. var propertyDescriptor = serializedProperties[property];
  7869. var targetPropertyName = propertyDescriptor.sourceName || property;
  7870. var propertyType = propertyDescriptor.type;
  7871. var sourceProperty = entity[property];
  7872. if (sourceProperty !== undefined && sourceProperty !== null) {
  7873. switch (propertyType) {
  7874. case 0: // Value
  7875. serializationObject[targetPropertyName] = sourceProperty;
  7876. break;
  7877. case 1: // Texture
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 2: // Color3
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 3: // FresnelParameters
  7884. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7885. break;
  7886. case 4: // Vector2
  7887. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7888. break;
  7889. case 5: // Vector3
  7890. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7891. break;
  7892. case 6: // Mesh reference
  7893. serializationObject[targetPropertyName] = sourceProperty.id;
  7894. break;
  7895. case 7: // Color Curves
  7896. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7897. break;
  7898. case 8: // Color 4
  7899. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7900. break;
  7901. case 9: // Image Processing
  7902. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7903. break;
  7904. case 10: // Quaternion
  7905. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7906. break;
  7907. case 11: // Camera reference
  7908. serializationObject[targetPropertyName] = sourceProperty.id;
  7909. break;
  7910. }
  7911. }
  7912. }
  7913. return serializationObject;
  7914. };
  7915. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7916. if (rootUrl === void 0) { rootUrl = null; }
  7917. var destination = creationFunction();
  7918. if (!rootUrl) {
  7919. rootUrl = "";
  7920. }
  7921. // Tags
  7922. if (BABYLON.Tags) {
  7923. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7924. }
  7925. var classStore = getMergedStore(destination);
  7926. // Properties
  7927. for (var property in classStore) {
  7928. var propertyDescriptor = classStore[property];
  7929. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7930. var propertyType = propertyDescriptor.type;
  7931. if (sourceProperty !== undefined && sourceProperty !== null) {
  7932. var dest = destination;
  7933. switch (propertyType) {
  7934. case 0: // Value
  7935. dest[property] = sourceProperty;
  7936. break;
  7937. case 1: // Texture
  7938. if (scene) {
  7939. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7940. }
  7941. break;
  7942. case 2: // Color3
  7943. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7944. break;
  7945. case 3: // FresnelParameters
  7946. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7947. break;
  7948. case 4: // Vector2
  7949. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7950. break;
  7951. case 5: // Vector3
  7952. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7953. break;
  7954. case 6: // Mesh reference
  7955. if (scene) {
  7956. dest[property] = scene.getLastMeshByID(sourceProperty);
  7957. }
  7958. break;
  7959. case 7: // Color Curves
  7960. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7961. break;
  7962. case 8: // Color 4
  7963. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7964. break;
  7965. case 9: // Image Processing
  7966. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7967. break;
  7968. case 10: // Quaternion
  7969. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7970. break;
  7971. case 11: // Camera reference
  7972. if (scene) {
  7973. dest[property] = scene.getCameraByID(sourceProperty);
  7974. }
  7975. break;
  7976. }
  7977. }
  7978. }
  7979. return destination;
  7980. };
  7981. SerializationHelper.Clone = function (creationFunction, source) {
  7982. return _copySource(creationFunction, source, false);
  7983. };
  7984. SerializationHelper.Instanciate = function (creationFunction, source) {
  7985. return _copySource(creationFunction, source, true);
  7986. };
  7987. return SerializationHelper;
  7988. }());
  7989. BABYLON.SerializationHelper = SerializationHelper;
  7990. })(BABYLON || (BABYLON = {}));
  7991. //# sourceMappingURL=babylon.decorators.js.map
  7992. var BABYLON;
  7993. (function (BABYLON) {
  7994. /**
  7995. * Wrapper class for promise with external resolve and reject.
  7996. */
  7997. var Deferred = /** @class */ (function () {
  7998. /**
  7999. * Constructor for this deferred object.
  8000. */
  8001. function Deferred() {
  8002. var _this = this;
  8003. this.promise = new Promise(function (resolve, reject) {
  8004. _this._resolve = resolve;
  8005. _this._reject = reject;
  8006. });
  8007. }
  8008. Object.defineProperty(Deferred.prototype, "resolve", {
  8009. /**
  8010. * The resolve method of the promise associated with this deferred object.
  8011. */
  8012. get: function () {
  8013. return this._resolve;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Deferred.prototype, "reject", {
  8019. /**
  8020. * The reject method of the promise associated with this deferred object.
  8021. */
  8022. get: function () {
  8023. return this._reject;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. return Deferred;
  8029. }());
  8030. BABYLON.Deferred = Deferred;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.deferred.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * A class serves as a medium between the observable and its observers
  8037. */
  8038. var EventState = /** @class */ (function () {
  8039. /**
  8040. * Create a new EventState
  8041. * @param mask defines the mask associated with this state
  8042. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8043. * @param target defines the original target of the state
  8044. * @param currentTarget defines the current target of the state
  8045. */
  8046. function EventState(mask, skipNextObservers, target, currentTarget) {
  8047. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8048. this.initalize(mask, skipNextObservers, target, currentTarget);
  8049. }
  8050. /**
  8051. * Initialize the current event state
  8052. * @param mask defines the mask associated with this state
  8053. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8054. * @param target defines the original target of the state
  8055. * @param currentTarget defines the current target of the state
  8056. * @returns the current event state
  8057. */
  8058. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8059. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8060. this.mask = mask;
  8061. this.skipNextObservers = skipNextObservers;
  8062. this.target = target;
  8063. this.currentTarget = currentTarget;
  8064. return this;
  8065. };
  8066. return EventState;
  8067. }());
  8068. BABYLON.EventState = EventState;
  8069. /**
  8070. * Represent an Observer registered to a given Observable object.
  8071. */
  8072. var Observer = /** @class */ (function () {
  8073. /**
  8074. * Creates a new observer
  8075. * @param callback defines the callback to call when the observer is notified
  8076. * @param mask defines the mask of the observer (used to filter notifications)
  8077. * @param scope defines the current scope used to restore the JS context
  8078. */
  8079. function Observer(
  8080. /**
  8081. * Defines the callback to call when the observer is notified
  8082. */
  8083. callback,
  8084. /**
  8085. * Defines the mask of the observer (used to filter notifications)
  8086. */
  8087. mask,
  8088. /**
  8089. * Defines the current scope used to restore the JS context
  8090. */
  8091. scope) {
  8092. if (scope === void 0) { scope = null; }
  8093. this.callback = callback;
  8094. this.mask = mask;
  8095. this.scope = scope;
  8096. /** @hidden */
  8097. this._willBeUnregistered = false;
  8098. /**
  8099. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8100. */
  8101. this.unregisterOnNextCall = false;
  8102. }
  8103. return Observer;
  8104. }());
  8105. BABYLON.Observer = Observer;
  8106. /**
  8107. * Represent a list of observers registered to multiple Observables object.
  8108. */
  8109. var MultiObserver = /** @class */ (function () {
  8110. function MultiObserver() {
  8111. }
  8112. /**
  8113. * Release associated resources
  8114. */
  8115. MultiObserver.prototype.dispose = function () {
  8116. if (this._observers && this._observables) {
  8117. for (var index = 0; index < this._observers.length; index++) {
  8118. this._observables[index].remove(this._observers[index]);
  8119. }
  8120. }
  8121. this._observers = null;
  8122. this._observables = null;
  8123. };
  8124. /**
  8125. * Raise a callback when one of the observable will notify
  8126. * @param observables defines a list of observables to watch
  8127. * @param callback defines the callback to call on notification
  8128. * @param mask defines the mask used to filter notifications
  8129. * @param scope defines the current scope used to restore the JS context
  8130. * @returns the new MultiObserver
  8131. */
  8132. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8133. if (mask === void 0) { mask = -1; }
  8134. if (scope === void 0) { scope = null; }
  8135. var result = new MultiObserver();
  8136. result._observers = new Array();
  8137. result._observables = observables;
  8138. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8139. var observable = observables_1[_i];
  8140. var observer = observable.add(callback, mask, false, scope);
  8141. if (observer) {
  8142. result._observers.push(observer);
  8143. }
  8144. }
  8145. return result;
  8146. };
  8147. return MultiObserver;
  8148. }());
  8149. BABYLON.MultiObserver = MultiObserver;
  8150. /**
  8151. * The Observable class is a simple implementation of the Observable pattern.
  8152. *
  8153. * 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.
  8154. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8155. * 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).
  8156. * 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.
  8157. */
  8158. var Observable = /** @class */ (function () {
  8159. /**
  8160. * Creates a new observable
  8161. * @param onObserverAdded defines a callback to call when a new observer is added
  8162. */
  8163. function Observable(onObserverAdded) {
  8164. this._observers = new Array();
  8165. this._eventState = new EventState(0);
  8166. if (onObserverAdded) {
  8167. this._onObserverAdded = onObserverAdded;
  8168. }
  8169. }
  8170. /**
  8171. * Create a new Observer with the specified callback
  8172. * @param callback the callback that will be executed for that Observer
  8173. * @param mask the mask used to filter observers
  8174. * @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.
  8175. * @param scope optional scope for the callback to be called from
  8176. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8177. * @returns the new observer created for the callback
  8178. */
  8179. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8180. if (mask === void 0) { mask = -1; }
  8181. if (insertFirst === void 0) { insertFirst = false; }
  8182. if (scope === void 0) { scope = null; }
  8183. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8184. if (!callback) {
  8185. return null;
  8186. }
  8187. var observer = new Observer(callback, mask, scope);
  8188. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8189. if (insertFirst) {
  8190. this._observers.unshift(observer);
  8191. }
  8192. else {
  8193. this._observers.push(observer);
  8194. }
  8195. if (this._onObserverAdded) {
  8196. this._onObserverAdded(observer);
  8197. }
  8198. return observer;
  8199. };
  8200. /**
  8201. * Create a new Observer with the specified callback and unregisters after the next notification
  8202. * @param callback the callback that will be executed for that Observer
  8203. * @returns the new observer created for the callback
  8204. */
  8205. Observable.prototype.addOnce = function (callback) {
  8206. return this.add(callback, undefined, undefined, undefined, true);
  8207. };
  8208. /**
  8209. * Remove an Observer from the Observable object
  8210. * @param observer the instance of the Observer to remove
  8211. * @returns false if it doesn't belong to this Observable
  8212. */
  8213. Observable.prototype.remove = function (observer) {
  8214. if (!observer) {
  8215. return false;
  8216. }
  8217. var index = this._observers.indexOf(observer);
  8218. if (index !== -1) {
  8219. this._deferUnregister(observer);
  8220. return true;
  8221. }
  8222. return false;
  8223. };
  8224. /**
  8225. * Remove a callback from the Observable object
  8226. * @param callback the callback to remove
  8227. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8228. * @returns false if it doesn't belong to this Observable
  8229. */
  8230. Observable.prototype.removeCallback = function (callback, scope) {
  8231. for (var index = 0; index < this._observers.length; index++) {
  8232. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8233. this._deferUnregister(this._observers[index]);
  8234. return true;
  8235. }
  8236. }
  8237. return false;
  8238. };
  8239. Observable.prototype._deferUnregister = function (observer) {
  8240. var _this = this;
  8241. observer.unregisterOnNextCall = false;
  8242. observer._willBeUnregistered = true;
  8243. BABYLON.Tools.SetImmediate(function () {
  8244. _this._remove(observer);
  8245. });
  8246. };
  8247. // This should only be called when not iterating over _observers to avoid callback skipping.
  8248. // Removes an observer from the _observer Array.
  8249. Observable.prototype._remove = function (observer) {
  8250. if (!observer) {
  8251. return false;
  8252. }
  8253. var index = this._observers.indexOf(observer);
  8254. if (index !== -1) {
  8255. this._observers.splice(index, 1);
  8256. return true;
  8257. }
  8258. return false;
  8259. };
  8260. /**
  8261. * Notify all Observers by calling their respective callback with the given data
  8262. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8263. * @param eventData defines the data to send to all observers
  8264. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8265. * @param target defines the original target of the state
  8266. * @param currentTarget defines the current target of the state
  8267. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8268. */
  8269. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8270. if (mask === void 0) { mask = -1; }
  8271. if (!this._observers.length) {
  8272. return true;
  8273. }
  8274. var state = this._eventState;
  8275. state.mask = mask;
  8276. state.target = target;
  8277. state.currentTarget = currentTarget;
  8278. state.skipNextObservers = false;
  8279. state.lastReturnValue = eventData;
  8280. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8281. var obs = _a[_i];
  8282. if (obs._willBeUnregistered) {
  8283. continue;
  8284. }
  8285. if (obs.mask & mask) {
  8286. if (obs.scope) {
  8287. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8288. }
  8289. else {
  8290. state.lastReturnValue = obs.callback(eventData, state);
  8291. }
  8292. if (obs.unregisterOnNextCall) {
  8293. this._deferUnregister(obs);
  8294. }
  8295. }
  8296. if (state.skipNextObservers) {
  8297. return false;
  8298. }
  8299. }
  8300. return true;
  8301. };
  8302. /**
  8303. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8304. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8305. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8306. * and it is crucial that all callbacks will be executed.
  8307. * The order of the callbacks is kept, callbacks are not executed parallel.
  8308. *
  8309. * @param eventData The data to be sent to each callback
  8310. * @param mask is used to filter observers defaults to -1
  8311. * @param target defines the callback target (see EventState)
  8312. * @param currentTarget defines he current object in the bubbling phase
  8313. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8314. */
  8315. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8316. var _this = this;
  8317. if (mask === void 0) { mask = -1; }
  8318. // create an empty promise
  8319. var p = Promise.resolve(eventData);
  8320. // no observers? return this promise.
  8321. if (!this._observers.length) {
  8322. return p;
  8323. }
  8324. var state = this._eventState;
  8325. state.mask = mask;
  8326. state.target = target;
  8327. state.currentTarget = currentTarget;
  8328. state.skipNextObservers = false;
  8329. // execute one callback after another (not using Promise.all, the order is important)
  8330. this._observers.forEach(function (obs) {
  8331. if (state.skipNextObservers) {
  8332. return;
  8333. }
  8334. if (obs._willBeUnregistered) {
  8335. return;
  8336. }
  8337. if (obs.mask & mask) {
  8338. if (obs.scope) {
  8339. p = p.then(function (lastReturnedValue) {
  8340. state.lastReturnValue = lastReturnedValue;
  8341. return obs.callback.apply(obs.scope, [eventData, state]);
  8342. });
  8343. }
  8344. else {
  8345. p = p.then(function (lastReturnedValue) {
  8346. state.lastReturnValue = lastReturnedValue;
  8347. return obs.callback(eventData, state);
  8348. });
  8349. }
  8350. if (obs.unregisterOnNextCall) {
  8351. _this._deferUnregister(obs);
  8352. }
  8353. }
  8354. });
  8355. // return the eventData
  8356. return p.then(function () { return eventData; });
  8357. };
  8358. /**
  8359. * Notify a specific observer
  8360. * @param observer defines the observer to notify
  8361. * @param eventData defines the data to be sent to each callback
  8362. * @param mask is used to filter observers defaults to -1
  8363. */
  8364. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8365. if (mask === void 0) { mask = -1; }
  8366. var state = this._eventState;
  8367. state.mask = mask;
  8368. state.skipNextObservers = false;
  8369. observer.callback(eventData, state);
  8370. };
  8371. /**
  8372. * Gets a boolean indicating if the observable has at least one observer
  8373. * @returns true is the Observable has at least one Observer registered
  8374. */
  8375. Observable.prototype.hasObservers = function () {
  8376. return this._observers.length > 0;
  8377. };
  8378. /**
  8379. * Clear the list of observers
  8380. */
  8381. Observable.prototype.clear = function () {
  8382. this._observers = new Array();
  8383. this._onObserverAdded = null;
  8384. };
  8385. /**
  8386. * Clone the current observable
  8387. * @returns a new observable
  8388. */
  8389. Observable.prototype.clone = function () {
  8390. var result = new Observable();
  8391. result._observers = this._observers.slice(0);
  8392. return result;
  8393. };
  8394. /**
  8395. * Does this observable handles observer registered with a given mask
  8396. * @param mask defines the mask to be tested
  8397. * @return whether or not one observer registered with the given mask is handeled
  8398. **/
  8399. Observable.prototype.hasSpecificMask = function (mask) {
  8400. if (mask === void 0) { mask = -1; }
  8401. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8402. var obs = _a[_i];
  8403. if (obs.mask & mask || obs.mask === mask) {
  8404. return true;
  8405. }
  8406. }
  8407. return false;
  8408. };
  8409. return Observable;
  8410. }());
  8411. BABYLON.Observable = Observable;
  8412. })(BABYLON || (BABYLON = {}));
  8413. //# sourceMappingURL=babylon.observable.js.map
  8414. var BABYLON;
  8415. (function (BABYLON) {
  8416. var SmartArray = /** @class */ (function () {
  8417. function SmartArray(capacity) {
  8418. this.length = 0;
  8419. this.data = new Array(capacity);
  8420. this._id = SmartArray._GlobalId++;
  8421. }
  8422. SmartArray.prototype.push = function (value) {
  8423. this.data[this.length++] = value;
  8424. if (this.length > this.data.length) {
  8425. this.data.length *= 2;
  8426. }
  8427. };
  8428. SmartArray.prototype.forEach = function (func) {
  8429. for (var index = 0; index < this.length; index++) {
  8430. func(this.data[index]);
  8431. }
  8432. };
  8433. SmartArray.prototype.sort = function (compareFn) {
  8434. this.data.sort(compareFn);
  8435. };
  8436. SmartArray.prototype.reset = function () {
  8437. this.length = 0;
  8438. };
  8439. SmartArray.prototype.dispose = function () {
  8440. this.reset();
  8441. if (this.data) {
  8442. this.data.length = 0;
  8443. this.data = [];
  8444. }
  8445. };
  8446. SmartArray.prototype.concat = function (array) {
  8447. if (array.length === 0) {
  8448. return;
  8449. }
  8450. if (this.length + array.length > this.data.length) {
  8451. this.data.length = (this.length + array.length) * 2;
  8452. }
  8453. for (var index = 0; index < array.length; index++) {
  8454. this.data[this.length++] = (array.data || array)[index];
  8455. }
  8456. };
  8457. SmartArray.prototype.indexOf = function (value) {
  8458. var position = this.data.indexOf(value);
  8459. if (position >= this.length) {
  8460. return -1;
  8461. }
  8462. return position;
  8463. };
  8464. SmartArray.prototype.contains = function (value) {
  8465. return this.data.indexOf(value) !== -1;
  8466. };
  8467. // Statics
  8468. SmartArray._GlobalId = 0;
  8469. return SmartArray;
  8470. }());
  8471. BABYLON.SmartArray = SmartArray;
  8472. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8473. __extends(SmartArrayNoDuplicate, _super);
  8474. function SmartArrayNoDuplicate() {
  8475. var _this = _super !== null && _super.apply(this, arguments) || this;
  8476. _this._duplicateId = 0;
  8477. return _this;
  8478. }
  8479. SmartArrayNoDuplicate.prototype.push = function (value) {
  8480. _super.prototype.push.call(this, value);
  8481. if (!value.__smartArrayFlags) {
  8482. value.__smartArrayFlags = {};
  8483. }
  8484. value.__smartArrayFlags[this._id] = this._duplicateId;
  8485. };
  8486. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8487. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8488. return false;
  8489. }
  8490. this.push(value);
  8491. return true;
  8492. };
  8493. SmartArrayNoDuplicate.prototype.reset = function () {
  8494. _super.prototype.reset.call(this);
  8495. this._duplicateId++;
  8496. };
  8497. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8498. if (array.length === 0) {
  8499. return;
  8500. }
  8501. if (this.length + array.length > this.data.length) {
  8502. this.data.length = (this.length + array.length) * 2;
  8503. }
  8504. for (var index = 0; index < array.length; index++) {
  8505. var item = (array.data || array)[index];
  8506. this.pushNoDuplicate(item);
  8507. }
  8508. };
  8509. return SmartArrayNoDuplicate;
  8510. }(SmartArray));
  8511. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8512. })(BABYLON || (BABYLON = {}));
  8513. //# sourceMappingURL=babylon.smartArray.js.map
  8514. var BABYLON;
  8515. (function (BABYLON) {
  8516. /** Class used to store color gradient */
  8517. var ColorGradient = /** @class */ (function () {
  8518. function ColorGradient() {
  8519. }
  8520. /**
  8521. * Will get a color picked randomly between color1 and color2.
  8522. * If color2 is undefined then color1 will be used
  8523. * @param result defines the target Color4 to store the result in
  8524. */
  8525. ColorGradient.prototype.getColorToRef = function (result) {
  8526. if (!this.color2) {
  8527. result.copyFrom(this.color1);
  8528. return;
  8529. }
  8530. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8531. };
  8532. return ColorGradient;
  8533. }());
  8534. BABYLON.ColorGradient = ColorGradient;
  8535. /** Class used to store factor gradient */
  8536. var FactorGradient = /** @class */ (function () {
  8537. function FactorGradient() {
  8538. }
  8539. /**
  8540. * Will get a number picked randomly between factor1 and factor2.
  8541. * If factor2 is undefined then factor1 will be used
  8542. * @returns the picked number
  8543. */
  8544. FactorGradient.prototype.getFactor = function () {
  8545. if (this.factor2 === undefined) {
  8546. return this.factor1;
  8547. }
  8548. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8549. };
  8550. return FactorGradient;
  8551. }());
  8552. BABYLON.FactorGradient = FactorGradient;
  8553. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8554. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8555. var LoadFileError = /** @class */ (function (_super) {
  8556. __extends(LoadFileError, _super);
  8557. function LoadFileError(message, request) {
  8558. var _this = _super.call(this, message) || this;
  8559. _this.request = request;
  8560. _this.name = "LoadFileError";
  8561. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8562. return _this;
  8563. }
  8564. // Polyfill for Object.setPrototypeOf if necessary.
  8565. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8566. return LoadFileError;
  8567. }(Error));
  8568. BABYLON.LoadFileError = LoadFileError;
  8569. var RetryStrategy = /** @class */ (function () {
  8570. function RetryStrategy() {
  8571. }
  8572. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8573. if (maxRetries === void 0) { maxRetries = 3; }
  8574. if (baseInterval === void 0) { baseInterval = 500; }
  8575. return function (url, request, retryIndex) {
  8576. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8577. return -1;
  8578. }
  8579. return Math.pow(2, retryIndex) * baseInterval;
  8580. };
  8581. };
  8582. return RetryStrategy;
  8583. }());
  8584. BABYLON.RetryStrategy = RetryStrategy;
  8585. // Screenshots
  8586. var screenshotCanvas;
  8587. var cloneValue = function (source, destinationObject) {
  8588. if (!source)
  8589. return null;
  8590. if (source instanceof BABYLON.Mesh) {
  8591. return null;
  8592. }
  8593. if (source instanceof BABYLON.SubMesh) {
  8594. return source.clone(destinationObject);
  8595. }
  8596. else if (source.clone) {
  8597. return source.clone();
  8598. }
  8599. return null;
  8600. };
  8601. var Tools = /** @class */ (function () {
  8602. function Tools() {
  8603. }
  8604. /**
  8605. * Interpolates between a and b via alpha
  8606. * @param a The lower value (returned when alpha = 0)
  8607. * @param b The upper value (returned when alpha = 1)
  8608. * @param alpha The interpolation-factor
  8609. * @return The mixed value
  8610. */
  8611. Tools.Mix = function (a, b, alpha) {
  8612. return a * (1 - alpha) + b * alpha;
  8613. };
  8614. Tools.Instantiate = function (className) {
  8615. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8616. return Tools.RegisteredExternalClasses[className];
  8617. }
  8618. var arr = className.split(".");
  8619. var fn = (window || this);
  8620. for (var i = 0, len = arr.length; i < len; i++) {
  8621. fn = fn[arr[i]];
  8622. }
  8623. if (typeof fn !== "function") {
  8624. return null;
  8625. }
  8626. return fn;
  8627. };
  8628. /**
  8629. * Provides a slice function that will work even on IE
  8630. * @param data defines the array to slice
  8631. * @param start defines the start of the data (optional)
  8632. * @param end defines the end of the data (optional)
  8633. * @returns the new sliced array
  8634. */
  8635. Tools.Slice = function (data, start, end) {
  8636. if (data.slice) {
  8637. return data.slice(start, end);
  8638. }
  8639. return Array.prototype.slice.call(data, start, end);
  8640. };
  8641. Tools.SetImmediate = function (action) {
  8642. if (window.setImmediate) {
  8643. window.setImmediate(action);
  8644. }
  8645. else {
  8646. setTimeout(action, 1);
  8647. }
  8648. };
  8649. Tools.IsExponentOfTwo = function (value) {
  8650. var count = 1;
  8651. do {
  8652. count *= 2;
  8653. } while (count < value);
  8654. return count === value;
  8655. };
  8656. /**
  8657. * Returns the nearest 32-bit single precision float representation of a Number
  8658. * @param value A Number. If the parameter is of a different type, it will get converted
  8659. * to a number or to NaN if it cannot be converted
  8660. * @returns number
  8661. */
  8662. Tools.FloatRound = function (value) {
  8663. if (Math.fround) {
  8664. return Math.fround(value);
  8665. }
  8666. return (Tools._tmpFloatArray[0] = value);
  8667. };
  8668. /**
  8669. * Find the next highest power of two.
  8670. * @param x Number to start search from.
  8671. * @return Next highest power of two.
  8672. */
  8673. Tools.CeilingPOT = function (x) {
  8674. x--;
  8675. x |= x >> 1;
  8676. x |= x >> 2;
  8677. x |= x >> 4;
  8678. x |= x >> 8;
  8679. x |= x >> 16;
  8680. x++;
  8681. return x;
  8682. };
  8683. /**
  8684. * Find the next lowest power of two.
  8685. * @param x Number to start search from.
  8686. * @return Next lowest power of two.
  8687. */
  8688. Tools.FloorPOT = function (x) {
  8689. x = x | (x >> 1);
  8690. x = x | (x >> 2);
  8691. x = x | (x >> 4);
  8692. x = x | (x >> 8);
  8693. x = x | (x >> 16);
  8694. return x - (x >> 1);
  8695. };
  8696. /**
  8697. * Find the nearest power of two.
  8698. * @param x Number to start search from.
  8699. * @return Next nearest power of two.
  8700. */
  8701. Tools.NearestPOT = function (x) {
  8702. var c = Tools.CeilingPOT(x);
  8703. var f = Tools.FloorPOT(x);
  8704. return (c - x) > (x - f) ? f : c;
  8705. };
  8706. Tools.GetExponentOfTwo = function (value, max, mode) {
  8707. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8708. var pot;
  8709. switch (mode) {
  8710. case BABYLON.Engine.SCALEMODE_FLOOR:
  8711. pot = Tools.FloorPOT(value);
  8712. break;
  8713. case BABYLON.Engine.SCALEMODE_NEAREST:
  8714. pot = Tools.NearestPOT(value);
  8715. break;
  8716. case BABYLON.Engine.SCALEMODE_CEILING:
  8717. default:
  8718. pot = Tools.CeilingPOT(value);
  8719. break;
  8720. }
  8721. return Math.min(pot, max);
  8722. };
  8723. Tools.GetFilename = function (path) {
  8724. var index = path.lastIndexOf("/");
  8725. if (index < 0)
  8726. return path;
  8727. return path.substring(index + 1);
  8728. };
  8729. /**
  8730. * Extracts the "folder" part of a path (everything before the filename).
  8731. * @param uri The URI to extract the info from
  8732. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8733. * @returns The "folder" part of the path
  8734. */
  8735. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8736. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8737. var index = uri.lastIndexOf("/");
  8738. if (index < 0) {
  8739. if (returnUnchangedIfNoSlash) {
  8740. return uri;
  8741. }
  8742. return "";
  8743. }
  8744. return uri.substring(0, index + 1);
  8745. };
  8746. Tools.GetDOMTextContent = function (element) {
  8747. var result = "";
  8748. var child = element.firstChild;
  8749. while (child) {
  8750. if (child.nodeType === 3) {
  8751. result += child.textContent;
  8752. }
  8753. child = child.nextSibling;
  8754. }
  8755. return result;
  8756. };
  8757. Tools.ToDegrees = function (angle) {
  8758. return angle * 180 / Math.PI;
  8759. };
  8760. Tools.ToRadians = function (angle) {
  8761. return angle * Math.PI / 180;
  8762. };
  8763. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8764. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8765. var output = "";
  8766. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8767. var i = 0;
  8768. var bytes = new Uint8Array(buffer);
  8769. while (i < bytes.length) {
  8770. chr1 = bytes[i++];
  8771. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8772. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8773. enc1 = chr1 >> 2;
  8774. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8775. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8776. enc4 = chr3 & 63;
  8777. if (isNaN(chr2)) {
  8778. enc3 = enc4 = 64;
  8779. }
  8780. else if (isNaN(chr3)) {
  8781. enc4 = 64;
  8782. }
  8783. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8784. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8785. }
  8786. return "data:image/png;base64," + output;
  8787. };
  8788. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8789. if (bias === void 0) { bias = null; }
  8790. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8791. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8792. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8793. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8794. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8795. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8796. }
  8797. if (bias) {
  8798. minimum.x -= minimum.x * bias.x + bias.y;
  8799. minimum.y -= minimum.y * bias.x + bias.y;
  8800. minimum.z -= minimum.z * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. maximum.z += maximum.z * bias.x + bias.y;
  8804. }
  8805. return {
  8806. minimum: minimum,
  8807. maximum: maximum
  8808. };
  8809. };
  8810. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8811. if (bias === void 0) { bias = null; }
  8812. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8813. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8814. if (!stride) {
  8815. stride = 3;
  8816. }
  8817. for (var index = start; index < start + count; index++) {
  8818. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8819. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8820. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8821. }
  8822. if (bias) {
  8823. minimum.x -= minimum.x * bias.x + bias.y;
  8824. minimum.y -= minimum.y * bias.x + bias.y;
  8825. minimum.z -= minimum.z * bias.x + bias.y;
  8826. maximum.x += maximum.x * bias.x + bias.y;
  8827. maximum.y += maximum.y * bias.x + bias.y;
  8828. maximum.z += maximum.z * bias.x + bias.y;
  8829. }
  8830. return {
  8831. minimum: minimum,
  8832. maximum: maximum
  8833. };
  8834. };
  8835. Tools.Vector2ArrayFeeder = function (array) {
  8836. return function (index) {
  8837. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8838. var length = isFloatArray ? array.length / 2 : array.length;
  8839. if (index >= length) {
  8840. return null;
  8841. }
  8842. if (isFloatArray) {
  8843. var fa = array;
  8844. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8845. }
  8846. var a = array;
  8847. return a[index];
  8848. };
  8849. };
  8850. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8851. if (bias === void 0) { bias = null; }
  8852. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8853. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8854. var i = 0;
  8855. var cur = feeder(i++);
  8856. while (cur) {
  8857. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8858. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8859. cur = feeder(i++);
  8860. }
  8861. if (bias) {
  8862. minimum.x -= minimum.x * bias.x + bias.y;
  8863. minimum.y -= minimum.y * bias.x + bias.y;
  8864. maximum.x += maximum.x * bias.x + bias.y;
  8865. maximum.y += maximum.y * bias.x + bias.y;
  8866. }
  8867. return {
  8868. minimum: minimum,
  8869. maximum: maximum
  8870. };
  8871. };
  8872. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8873. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8874. return null;
  8875. return Array.isArray(obj) ? obj : [obj];
  8876. };
  8877. // Misc.
  8878. Tools.GetPointerPrefix = function () {
  8879. var eventPrefix = "pointer";
  8880. // Check if pointer events are supported
  8881. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8882. eventPrefix = "mouse";
  8883. }
  8884. return eventPrefix;
  8885. };
  8886. /**
  8887. * @param func - the function to be called
  8888. * @param requester - the object that will request the next frame. Falls back to window.
  8889. */
  8890. Tools.QueueNewFrame = function (func, requester) {
  8891. if (!Tools.IsWindowObjectExist()) {
  8892. return setTimeout(func, 16);
  8893. }
  8894. if (!requester) {
  8895. requester = window;
  8896. }
  8897. if (requester.requestAnimationFrame) {
  8898. return requester.requestAnimationFrame(func);
  8899. }
  8900. else if (requester.msRequestAnimationFrame) {
  8901. return requester.msRequestAnimationFrame(func);
  8902. }
  8903. else if (requester.webkitRequestAnimationFrame) {
  8904. return requester.webkitRequestAnimationFrame(func);
  8905. }
  8906. else if (requester.mozRequestAnimationFrame) {
  8907. return requester.mozRequestAnimationFrame(func);
  8908. }
  8909. else if (requester.oRequestAnimationFrame) {
  8910. return requester.oRequestAnimationFrame(func);
  8911. }
  8912. else {
  8913. return window.setTimeout(func, 16);
  8914. }
  8915. };
  8916. Tools.RequestFullscreen = function (element) {
  8917. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8918. if (!requestFunction)
  8919. return;
  8920. requestFunction.call(element);
  8921. };
  8922. Tools.ExitFullscreen = function () {
  8923. if (document.exitFullscreen) {
  8924. document.exitFullscreen();
  8925. }
  8926. else if (document.mozCancelFullScreen) {
  8927. document.mozCancelFullScreen();
  8928. }
  8929. else if (document.webkitCancelFullScreen) {
  8930. document.webkitCancelFullScreen();
  8931. }
  8932. else if (document.msCancelFullScreen) {
  8933. document.msCancelFullScreen();
  8934. }
  8935. };
  8936. Tools.SetCorsBehavior = function (url, element) {
  8937. if (url && url.indexOf("data:") === 0) {
  8938. return;
  8939. }
  8940. if (Tools.CorsBehavior) {
  8941. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8942. element.crossOrigin = Tools.CorsBehavior;
  8943. }
  8944. else {
  8945. var result = Tools.CorsBehavior(url);
  8946. if (result) {
  8947. element.crossOrigin = result;
  8948. }
  8949. }
  8950. }
  8951. };
  8952. // External files
  8953. Tools.CleanUrl = function (url) {
  8954. url = url.replace(/#/mg, "%23");
  8955. return url;
  8956. };
  8957. /**
  8958. * Loads an image as an HTMLImageElement.
  8959. * @param input url string, ArrayBuffer, or Blob to load
  8960. * @param onLoad callback called when the image successfully loads
  8961. * @param onError callback called when the image fails to load
  8962. * @param database database for caching
  8963. * @returns the HTMLImageElement of the loaded image
  8964. */
  8965. Tools.LoadImage = function (input, onLoad, onError, database) {
  8966. var url;
  8967. var usingObjectURL = false;
  8968. if (input instanceof ArrayBuffer) {
  8969. url = URL.createObjectURL(new Blob([input]));
  8970. usingObjectURL = true;
  8971. }
  8972. else if (input instanceof Blob) {
  8973. url = URL.createObjectURL(input);
  8974. usingObjectURL = true;
  8975. }
  8976. else {
  8977. url = Tools.CleanUrl(input);
  8978. url = Tools.PreprocessUrl(input);
  8979. }
  8980. var img = new Image();
  8981. Tools.SetCorsBehavior(url, img);
  8982. var loadHandler = function () {
  8983. if (usingObjectURL && img.src) {
  8984. URL.revokeObjectURL(img.src);
  8985. }
  8986. img.removeEventListener("load", loadHandler);
  8987. img.removeEventListener("error", errorHandler);
  8988. onLoad(img);
  8989. };
  8990. var errorHandler = function (err) {
  8991. if (usingObjectURL && img.src) {
  8992. URL.revokeObjectURL(img.src);
  8993. }
  8994. img.removeEventListener("load", loadHandler);
  8995. img.removeEventListener("error", errorHandler);
  8996. Tools.Error("Error while trying to load image: " + input);
  8997. if (onError) {
  8998. onError("Error while trying to load image: " + input, err);
  8999. }
  9000. };
  9001. img.addEventListener("load", loadHandler);
  9002. img.addEventListener("error", errorHandler);
  9003. var noIndexedDB = function () {
  9004. img.src = url;
  9005. };
  9006. var loadFromIndexedDB = function () {
  9007. if (database) {
  9008. database.loadImageFromDB(url, img);
  9009. }
  9010. };
  9011. //ANY database to do!
  9012. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9013. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9014. }
  9015. else {
  9016. if (url.indexOf("file:") !== -1) {
  9017. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9018. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9019. try {
  9020. var blobURL;
  9021. try {
  9022. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9023. }
  9024. catch (ex) {
  9025. // Chrome doesn't support oneTimeOnly parameter
  9026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9027. }
  9028. img.src = blobURL;
  9029. usingObjectURL = true;
  9030. }
  9031. catch (e) {
  9032. img.src = "";
  9033. }
  9034. return img;
  9035. }
  9036. }
  9037. noIndexedDB();
  9038. }
  9039. return img;
  9040. };
  9041. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9042. url = Tools.CleanUrl(url);
  9043. url = Tools.PreprocessUrl(url);
  9044. // If file and file input are set
  9045. if (url.indexOf("file:") !== -1) {
  9046. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9047. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9048. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9049. }
  9050. }
  9051. var loadUrl = Tools.BaseUrl + url;
  9052. var aborted = false;
  9053. var fileRequest = {
  9054. onCompleteObservable: new BABYLON.Observable(),
  9055. abort: function () { return aborted = true; },
  9056. };
  9057. var requestFile = function () {
  9058. var request = new XMLHttpRequest();
  9059. var retryHandle = null;
  9060. fileRequest.abort = function () {
  9061. aborted = true;
  9062. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9063. request.abort();
  9064. }
  9065. if (retryHandle !== null) {
  9066. clearTimeout(retryHandle);
  9067. retryHandle = null;
  9068. }
  9069. };
  9070. var retryLoop = function (retryIndex) {
  9071. request.open('GET', loadUrl, true);
  9072. if (useArrayBuffer) {
  9073. request.responseType = "arraybuffer";
  9074. }
  9075. if (onProgress) {
  9076. request.addEventListener("progress", onProgress);
  9077. }
  9078. var onLoadEnd = function () {
  9079. request.removeEventListener("loadend", onLoadEnd);
  9080. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9081. fileRequest.onCompleteObservable.clear();
  9082. };
  9083. request.addEventListener("loadend", onLoadEnd);
  9084. var onReadyStateChange = function () {
  9085. if (aborted) {
  9086. return;
  9087. }
  9088. // In case of undefined state in some browsers.
  9089. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9090. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9091. request.removeEventListener("readystatechange", onReadyStateChange);
  9092. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9093. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9094. return;
  9095. }
  9096. var retryStrategy = Tools.DefaultRetryStrategy;
  9097. if (retryStrategy) {
  9098. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9099. if (waitTime !== -1) {
  9100. // Prevent the request from completing for retry.
  9101. request.removeEventListener("loadend", onLoadEnd);
  9102. request = new XMLHttpRequest();
  9103. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9104. return;
  9105. }
  9106. }
  9107. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9108. if (onError) {
  9109. onError(request, e);
  9110. }
  9111. else {
  9112. throw e;
  9113. }
  9114. }
  9115. };
  9116. request.addEventListener("readystatechange", onReadyStateChange);
  9117. request.send();
  9118. };
  9119. retryLoop(0);
  9120. };
  9121. // Caching all files
  9122. if (database && database.enableSceneOffline) {
  9123. var noIndexedDB_1 = function () {
  9124. if (!aborted) {
  9125. requestFile();
  9126. }
  9127. };
  9128. var loadFromIndexedDB = function () {
  9129. // TODO: database needs to support aborting and should return a IFileRequest
  9130. if (aborted) {
  9131. return;
  9132. }
  9133. if (database) {
  9134. database.loadFileFromDB(url, function (data) {
  9135. if (!aborted) {
  9136. onSuccess(data);
  9137. }
  9138. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9139. }, onProgress ? function (event) {
  9140. if (!aborted) {
  9141. onProgress(event);
  9142. }
  9143. } : undefined, noIndexedDB_1, useArrayBuffer);
  9144. }
  9145. };
  9146. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9147. }
  9148. else {
  9149. requestFile();
  9150. }
  9151. return fileRequest;
  9152. };
  9153. /**
  9154. * Load a script (identified by an url). When the url returns, the
  9155. * content of this file is added into a new script element, attached to the DOM (body element)
  9156. */
  9157. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9158. var head = document.getElementsByTagName('head')[0];
  9159. var script = document.createElement('script');
  9160. script.type = 'text/javascript';
  9161. script.src = scriptUrl;
  9162. script.onload = function () {
  9163. if (onSuccess) {
  9164. onSuccess();
  9165. }
  9166. };
  9167. script.onerror = function (e) {
  9168. if (onError) {
  9169. onError("Unable to load script '" + scriptUrl + "'", e);
  9170. }
  9171. };
  9172. head.appendChild(script);
  9173. };
  9174. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9175. var reader = new FileReader();
  9176. var request = {
  9177. onCompleteObservable: new BABYLON.Observable(),
  9178. abort: function () { return reader.abort(); },
  9179. };
  9180. reader.onloadend = function (e) {
  9181. request.onCompleteObservable.notifyObservers(request);
  9182. };
  9183. reader.onload = function (e) {
  9184. //target doesn't have result from ts 1.3
  9185. callback(e.target['result']);
  9186. };
  9187. reader.onprogress = progressCallback;
  9188. reader.readAsDataURL(fileToLoad);
  9189. return request;
  9190. };
  9191. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9192. var reader = new FileReader();
  9193. var request = {
  9194. onCompleteObservable: new BABYLON.Observable(),
  9195. abort: function () { return reader.abort(); },
  9196. };
  9197. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9198. reader.onerror = function (e) {
  9199. Tools.Log("Error while reading file: " + fileToLoad.name);
  9200. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9201. };
  9202. reader.onload = function (e) {
  9203. //target doesn't have result from ts 1.3
  9204. callback(e.target['result']);
  9205. };
  9206. if (progressCallBack) {
  9207. reader.onprogress = progressCallBack;
  9208. }
  9209. if (!useArrayBuffer) {
  9210. // Asynchronous read
  9211. reader.readAsText(fileToLoad);
  9212. }
  9213. else {
  9214. reader.readAsArrayBuffer(fileToLoad);
  9215. }
  9216. return request;
  9217. };
  9218. //returns a downloadable url to a file content.
  9219. Tools.FileAsURL = function (content) {
  9220. var fileBlob = new Blob([content]);
  9221. var url = window.URL || window.webkitURL;
  9222. var link = url.createObjectURL(fileBlob);
  9223. return link;
  9224. };
  9225. // Misc.
  9226. Tools.Format = function (value, decimals) {
  9227. if (decimals === void 0) { decimals = 2; }
  9228. return value.toFixed(decimals);
  9229. };
  9230. Tools.CheckExtends = function (v, min, max) {
  9231. if (v.x < min.x)
  9232. min.x = v.x;
  9233. if (v.y < min.y)
  9234. min.y = v.y;
  9235. if (v.z < min.z)
  9236. min.z = v.z;
  9237. if (v.x > max.x)
  9238. max.x = v.x;
  9239. if (v.y > max.y)
  9240. max.y = v.y;
  9241. if (v.z > max.z)
  9242. max.z = v.z;
  9243. };
  9244. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9245. for (var prop in source) {
  9246. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9247. continue;
  9248. }
  9249. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9250. continue;
  9251. }
  9252. var sourceValue = source[prop];
  9253. var typeOfSourceValue = typeof sourceValue;
  9254. if (typeOfSourceValue === "function") {
  9255. continue;
  9256. }
  9257. try {
  9258. if (typeOfSourceValue === "object") {
  9259. if (sourceValue instanceof Array) {
  9260. destination[prop] = [];
  9261. if (sourceValue.length > 0) {
  9262. if (typeof sourceValue[0] == "object") {
  9263. for (var index = 0; index < sourceValue.length; index++) {
  9264. var clonedValue = cloneValue(sourceValue[index], destination);
  9265. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9266. destination[prop].push(clonedValue);
  9267. }
  9268. }
  9269. }
  9270. else {
  9271. destination[prop] = sourceValue.slice(0);
  9272. }
  9273. }
  9274. }
  9275. else {
  9276. destination[prop] = cloneValue(sourceValue, destination);
  9277. }
  9278. }
  9279. else {
  9280. destination[prop] = sourceValue;
  9281. }
  9282. }
  9283. catch (e) {
  9284. // Just ignore error (it could be because of a read-only property)
  9285. }
  9286. }
  9287. };
  9288. Tools.IsEmpty = function (obj) {
  9289. for (var i in obj) {
  9290. if (obj.hasOwnProperty(i)) {
  9291. return false;
  9292. }
  9293. }
  9294. return true;
  9295. };
  9296. Tools.RegisterTopRootEvents = function (events) {
  9297. for (var index = 0; index < events.length; index++) {
  9298. var event = events[index];
  9299. window.addEventListener(event.name, event.handler, false);
  9300. try {
  9301. if (window.parent) {
  9302. window.parent.addEventListener(event.name, event.handler, false);
  9303. }
  9304. }
  9305. catch (e) {
  9306. // Silently fails...
  9307. }
  9308. }
  9309. };
  9310. Tools.UnregisterTopRootEvents = function (events) {
  9311. for (var index = 0; index < events.length; index++) {
  9312. var event = events[index];
  9313. window.removeEventListener(event.name, event.handler);
  9314. try {
  9315. if (window.parent) {
  9316. window.parent.removeEventListener(event.name, event.handler);
  9317. }
  9318. }
  9319. catch (e) {
  9320. // Silently fails...
  9321. }
  9322. }
  9323. };
  9324. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9325. if (mimeType === void 0) { mimeType = "image/png"; }
  9326. // Read the contents of the framebuffer
  9327. var numberOfChannelsByLine = width * 4;
  9328. var halfHeight = height / 2;
  9329. //Reading datas from WebGL
  9330. var data = engine.readPixels(0, 0, width, height);
  9331. //To flip image on Y axis.
  9332. for (var i = 0; i < halfHeight; i++) {
  9333. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9334. var currentCell = j + i * numberOfChannelsByLine;
  9335. var targetLine = height - i - 1;
  9336. var targetCell = j + targetLine * numberOfChannelsByLine;
  9337. var temp = data[currentCell];
  9338. data[currentCell] = data[targetCell];
  9339. data[targetCell] = temp;
  9340. }
  9341. }
  9342. // Create a 2D canvas to store the result
  9343. if (!screenshotCanvas) {
  9344. screenshotCanvas = document.createElement('canvas');
  9345. }
  9346. screenshotCanvas.width = width;
  9347. screenshotCanvas.height = height;
  9348. var context = screenshotCanvas.getContext('2d');
  9349. if (context) {
  9350. // Copy the pixels to a 2D canvas
  9351. var imageData = context.createImageData(width, height);
  9352. var castData = (imageData.data);
  9353. castData.set(data);
  9354. context.putImageData(imageData, 0, 0);
  9355. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9356. }
  9357. };
  9358. /**
  9359. * Converts the canvas data to blob.
  9360. * This acts as a polyfill for browsers not supporting the to blob function.
  9361. * @param canvas Defines the canvas to extract the data from
  9362. * @param successCallback Defines the callback triggered once the data are available
  9363. * @param mimeType Defines the mime type of the result
  9364. */
  9365. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9366. if (mimeType === void 0) { mimeType = "image/png"; }
  9367. // We need HTMLCanvasElement.toBlob for HD screenshots
  9368. if (!canvas.toBlob) {
  9369. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9370. canvas.toBlob = function (callback, type, quality) {
  9371. var _this = this;
  9372. setTimeout(function () {
  9373. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9374. for (var i = 0; i < len; i++) {
  9375. arr[i] = binStr.charCodeAt(i);
  9376. }
  9377. callback(new Blob([arr]));
  9378. });
  9379. };
  9380. }
  9381. canvas.toBlob(function (blob) {
  9382. successCallback(blob);
  9383. }, mimeType);
  9384. };
  9385. /**
  9386. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9387. * @param successCallback Defines the callback triggered once the data are available
  9388. * @param mimeType Defines the mime type of the result
  9389. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9390. */
  9391. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9392. if (mimeType === void 0) { mimeType = "image/png"; }
  9393. if (successCallback) {
  9394. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9395. successCallback(base64Image);
  9396. }
  9397. else {
  9398. this.ToBlob(screenshotCanvas, function (blob) {
  9399. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9400. if (("download" in document.createElement("a"))) {
  9401. if (!fileName) {
  9402. var date = new Date();
  9403. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9404. fileName = "screenshot_" + stringDate + ".png";
  9405. }
  9406. Tools.Download(blob, fileName);
  9407. }
  9408. else {
  9409. var url = URL.createObjectURL(blob);
  9410. var newWindow = window.open("");
  9411. if (!newWindow)
  9412. return;
  9413. var img = newWindow.document.createElement("img");
  9414. img.onload = function () {
  9415. // no longer need to read the blob so it's revoked
  9416. URL.revokeObjectURL(url);
  9417. };
  9418. img.src = url;
  9419. newWindow.document.body.appendChild(img);
  9420. }
  9421. }, mimeType);
  9422. }
  9423. };
  9424. /**
  9425. * Downloads a blob in the browser
  9426. * @param blob defines the blob to download
  9427. * @param fileName defines the name of the downloaded file
  9428. */
  9429. Tools.Download = function (blob, fileName) {
  9430. var url = window.URL.createObjectURL(blob);
  9431. var a = document.createElement("a");
  9432. document.body.appendChild(a);
  9433. a.style.display = "none";
  9434. a.href = url;
  9435. a.download = fileName;
  9436. a.addEventListener("click", function () {
  9437. if (a.parentElement) {
  9438. a.parentElement.removeChild(a);
  9439. }
  9440. });
  9441. a.click();
  9442. window.URL.revokeObjectURL(url);
  9443. };
  9444. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9445. if (mimeType === void 0) { mimeType = "image/png"; }
  9446. var width;
  9447. var height;
  9448. // If a precision value is specified
  9449. if (size.precision) {
  9450. width = Math.round(engine.getRenderWidth() * size.precision);
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. }
  9453. else if (size.width && size.height) {
  9454. width = size.width;
  9455. height = size.height;
  9456. }
  9457. //If passing only width, computing height to keep display canvas ratio.
  9458. else if (size.width && !size.height) {
  9459. width = size.width;
  9460. height = Math.round(width / engine.getAspectRatio(camera));
  9461. }
  9462. //If passing only height, computing width to keep display canvas ratio.
  9463. else if (size.height && !size.width) {
  9464. height = size.height;
  9465. width = Math.round(height * engine.getAspectRatio(camera));
  9466. }
  9467. //Assuming here that "size" parameter is a number
  9468. else if (!isNaN(size)) {
  9469. height = size;
  9470. width = size;
  9471. }
  9472. else {
  9473. Tools.Error("Invalid 'size' parameter !");
  9474. return;
  9475. }
  9476. if (!screenshotCanvas) {
  9477. screenshotCanvas = document.createElement('canvas');
  9478. }
  9479. screenshotCanvas.width = width;
  9480. screenshotCanvas.height = height;
  9481. var renderContext = screenshotCanvas.getContext("2d");
  9482. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9483. var newWidth = width;
  9484. var newHeight = newWidth / ratio;
  9485. if (newHeight > height) {
  9486. newHeight = height;
  9487. newWidth = newHeight * ratio;
  9488. }
  9489. var offsetX = Math.max(0, width - newWidth) / 2;
  9490. var offsetY = Math.max(0, height - newHeight) / 2;
  9491. var renderingCanvas = engine.getRenderingCanvas();
  9492. if (renderContext && renderingCanvas) {
  9493. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9494. }
  9495. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9496. };
  9497. /**
  9498. * Generates an image screenshot from the specified camera.
  9499. *
  9500. * @param engine The engine to use for rendering
  9501. * @param camera The camera to use for rendering
  9502. * @param size This parameter can be set to a single number or to an object with the
  9503. * following (optional) properties: precision, width, height. If a single number is passed,
  9504. * it will be used for both width and height. If an object is passed, the screenshot size
  9505. * will be derived from the parameters. The precision property is a multiplier allowing
  9506. * rendering at a higher or lower resolution.
  9507. * @param successCallback The callback receives a single parameter which contains the
  9508. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9509. * src parameter of an <img> to display it.
  9510. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9511. * Check your browser for supported MIME types.
  9512. * @param samples Texture samples (default: 1)
  9513. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9514. * @param fileName A name for for the downloaded file.
  9515. * @constructor
  9516. */
  9517. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. if (samples === void 0) { samples = 1; }
  9520. if (antialiasing === void 0) { antialiasing = false; }
  9521. var width;
  9522. var height;
  9523. //If a precision value is specified
  9524. if (size.precision) {
  9525. width = Math.round(engine.getRenderWidth() * size.precision);
  9526. height = Math.round(width / engine.getAspectRatio(camera));
  9527. size = { width: width, height: height };
  9528. }
  9529. else if (size.width && size.height) {
  9530. width = size.width;
  9531. height = size.height;
  9532. }
  9533. //If passing only width, computing height to keep display canvas ratio.
  9534. else if (size.width && !size.height) {
  9535. width = size.width;
  9536. height = Math.round(width / engine.getAspectRatio(camera));
  9537. size = { width: width, height: height };
  9538. }
  9539. //If passing only height, computing width to keep display canvas ratio.
  9540. else if (size.height && !size.width) {
  9541. height = size.height;
  9542. width = Math.round(height * engine.getAspectRatio(camera));
  9543. size = { width: width, height: height };
  9544. }
  9545. //Assuming here that "size" parameter is a number
  9546. else if (!isNaN(size)) {
  9547. height = size;
  9548. width = size;
  9549. }
  9550. else {
  9551. Tools.Error("Invalid 'size' parameter !");
  9552. return;
  9553. }
  9554. var scene = camera.getScene();
  9555. var previousCamera = null;
  9556. if (scene.activeCamera !== camera) {
  9557. previousCamera = scene.activeCamera;
  9558. scene.activeCamera = camera;
  9559. }
  9560. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9561. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9562. texture.renderList = null;
  9563. texture.samples = samples;
  9564. if (antialiasing) {
  9565. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9566. }
  9567. texture.onAfterRenderObservable.add(function () {
  9568. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9569. });
  9570. scene.incrementRenderId();
  9571. scene.resetCachedMaterial();
  9572. texture.render(true);
  9573. texture.dispose();
  9574. if (previousCamera) {
  9575. scene.activeCamera = previousCamera;
  9576. }
  9577. camera.getProjectionMatrix(true); // Force cache refresh;
  9578. };
  9579. // XHR response validator for local file scenario
  9580. Tools.ValidateXHRData = function (xhr, dataType) {
  9581. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9582. if (dataType === void 0) { dataType = 7; }
  9583. try {
  9584. if (dataType & 1) {
  9585. if (xhr.responseText && xhr.responseText.length > 0) {
  9586. return true;
  9587. }
  9588. else if (dataType === 1) {
  9589. return false;
  9590. }
  9591. }
  9592. if (dataType & 2) {
  9593. // Check header width and height since there is no "TGA" magic number
  9594. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9595. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9596. return true;
  9597. }
  9598. else if (dataType === 2) {
  9599. return false;
  9600. }
  9601. }
  9602. if (dataType & 4) {
  9603. // Check for the "DDS" magic number
  9604. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9605. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9606. return true;
  9607. }
  9608. else {
  9609. return false;
  9610. }
  9611. }
  9612. }
  9613. catch (e) {
  9614. // Global protection
  9615. }
  9616. return false;
  9617. };
  9618. /**
  9619. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9620. * Be aware Math.random() could cause collisions, but:
  9621. * "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"
  9622. */
  9623. Tools.RandomId = function () {
  9624. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9625. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9626. return v.toString(16);
  9627. });
  9628. };
  9629. /**
  9630. * Test if the given uri is a base64 string.
  9631. * @param uri The uri to test
  9632. * @return True if the uri is a base64 string or false otherwise.
  9633. */
  9634. Tools.IsBase64 = function (uri) {
  9635. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9636. };
  9637. /**
  9638. * Decode the given base64 uri.
  9639. * @param uri The uri to decode
  9640. * @return The decoded base64 data.
  9641. */
  9642. Tools.DecodeBase64 = function (uri) {
  9643. var decodedString = atob(uri.split(",")[1]);
  9644. var bufferLength = decodedString.length;
  9645. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9646. for (var i = 0; i < bufferLength; i++) {
  9647. bufferView[i] = decodedString.charCodeAt(i);
  9648. }
  9649. return bufferView.buffer;
  9650. };
  9651. Object.defineProperty(Tools, "NoneLogLevel", {
  9652. get: function () {
  9653. return Tools._NoneLogLevel;
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Object.defineProperty(Tools, "MessageLogLevel", {
  9659. get: function () {
  9660. return Tools._MessageLogLevel;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Tools, "WarningLogLevel", {
  9666. get: function () {
  9667. return Tools._WarningLogLevel;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Tools, "ErrorLogLevel", {
  9673. get: function () {
  9674. return Tools._ErrorLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "AllLogLevel", {
  9680. get: function () {
  9681. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Tools._AddLogEntry = function (entry) {
  9687. Tools._LogCache = entry + Tools._LogCache;
  9688. if (Tools.OnNewCacheEntry) {
  9689. Tools.OnNewCacheEntry(entry);
  9690. }
  9691. };
  9692. Tools._FormatMessage = function (message) {
  9693. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9694. var date = new Date();
  9695. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9696. };
  9697. Tools._LogDisabled = function (message) {
  9698. // nothing to do
  9699. };
  9700. Tools._LogEnabled = function (message) {
  9701. var formattedMessage = Tools._FormatMessage(message);
  9702. console.log("BJS - " + formattedMessage);
  9703. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9704. Tools._AddLogEntry(entry);
  9705. };
  9706. Tools._WarnDisabled = function (message) {
  9707. // nothing to do
  9708. };
  9709. Tools._WarnEnabled = function (message) {
  9710. var formattedMessage = Tools._FormatMessage(message);
  9711. console.warn("BJS - " + formattedMessage);
  9712. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9713. Tools._AddLogEntry(entry);
  9714. };
  9715. Tools._ErrorDisabled = function (message) {
  9716. // nothing to do
  9717. };
  9718. Tools._ErrorEnabled = function (message) {
  9719. Tools.errorsCount++;
  9720. var formattedMessage = Tools._FormatMessage(message);
  9721. console.error("BJS - " + formattedMessage);
  9722. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9723. Tools._AddLogEntry(entry);
  9724. };
  9725. Object.defineProperty(Tools, "LogCache", {
  9726. get: function () {
  9727. return Tools._LogCache;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools.ClearLogCache = function () {
  9733. Tools._LogCache = "";
  9734. Tools.errorsCount = 0;
  9735. };
  9736. Object.defineProperty(Tools, "LogLevels", {
  9737. set: function (level) {
  9738. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9739. Tools.Log = Tools._LogEnabled;
  9740. }
  9741. else {
  9742. Tools.Log = Tools._LogDisabled;
  9743. }
  9744. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9745. Tools.Warn = Tools._WarnEnabled;
  9746. }
  9747. else {
  9748. Tools.Warn = Tools._WarnDisabled;
  9749. }
  9750. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9751. Tools.Error = Tools._ErrorEnabled;
  9752. }
  9753. else {
  9754. Tools.Error = Tools._ErrorDisabled;
  9755. }
  9756. },
  9757. enumerable: true,
  9758. configurable: true
  9759. });
  9760. Tools.IsWindowObjectExist = function () {
  9761. return (typeof window) !== "undefined";
  9762. };
  9763. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9764. get: function () {
  9765. return Tools._PerformanceNoneLogLevel;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9771. get: function () {
  9772. return Tools._PerformanceUserMarkLogLevel;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9778. get: function () {
  9779. return Tools._PerformanceConsoleLogLevel;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9785. set: function (level) {
  9786. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9787. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9788. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9789. return;
  9790. }
  9791. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9792. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9793. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9794. return;
  9795. }
  9796. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9797. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9803. };
  9804. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9805. };
  9806. Tools._StartUserMark = function (counterName, condition) {
  9807. if (condition === void 0) { condition = true; }
  9808. if (!Tools._performance) {
  9809. if (!Tools.IsWindowObjectExist()) {
  9810. return;
  9811. }
  9812. Tools._performance = window.performance;
  9813. }
  9814. if (!condition || !Tools._performance.mark) {
  9815. return;
  9816. }
  9817. Tools._performance.mark(counterName + "-Begin");
  9818. };
  9819. Tools._EndUserMark = function (counterName, condition) {
  9820. if (condition === void 0) { condition = true; }
  9821. if (!condition || !Tools._performance.mark) {
  9822. return;
  9823. }
  9824. Tools._performance.mark(counterName + "-End");
  9825. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9826. };
  9827. Tools._StartPerformanceConsole = function (counterName, condition) {
  9828. if (condition === void 0) { condition = true; }
  9829. if (!condition) {
  9830. return;
  9831. }
  9832. Tools._StartUserMark(counterName, condition);
  9833. if (console.time) {
  9834. console.time(counterName);
  9835. }
  9836. };
  9837. Tools._EndPerformanceConsole = function (counterName, condition) {
  9838. if (condition === void 0) { condition = true; }
  9839. if (!condition) {
  9840. return;
  9841. }
  9842. Tools._EndUserMark(counterName, condition);
  9843. if (console.time) {
  9844. console.timeEnd(counterName);
  9845. }
  9846. };
  9847. Object.defineProperty(Tools, "Now", {
  9848. get: function () {
  9849. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9850. return window.performance.now();
  9851. }
  9852. return Date.now();
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. /**
  9858. * This method will return the name of the class used to create the instance of the given object.
  9859. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9860. * @param object the object to get the class name from
  9861. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9862. */
  9863. Tools.GetClassName = function (object, isType) {
  9864. if (isType === void 0) { isType = false; }
  9865. var name = null;
  9866. if (!isType && object.getClassName) {
  9867. name = object.getClassName();
  9868. }
  9869. else {
  9870. if (object instanceof Object) {
  9871. var classObj = isType ? object : Object.getPrototypeOf(object);
  9872. name = classObj.constructor["__bjsclassName__"];
  9873. }
  9874. if (!name) {
  9875. name = typeof object;
  9876. }
  9877. }
  9878. return name;
  9879. };
  9880. Tools.First = function (array, predicate) {
  9881. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9882. var el = array_1[_i];
  9883. if (predicate(el)) {
  9884. return el;
  9885. }
  9886. }
  9887. return null;
  9888. };
  9889. /**
  9890. * This method will return the name of the full name of the class, including its owning module (if any).
  9891. * 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).
  9892. * @param object the object to get the class name from
  9893. * @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.
  9894. */
  9895. Tools.getFullClassName = function (object, isType) {
  9896. if (isType === void 0) { isType = false; }
  9897. var className = null;
  9898. var moduleName = null;
  9899. if (!isType && object.getClassName) {
  9900. className = object.getClassName();
  9901. }
  9902. else {
  9903. if (object instanceof Object) {
  9904. var classObj = isType ? object : Object.getPrototypeOf(object);
  9905. className = classObj.constructor["__bjsclassName__"];
  9906. moduleName = classObj.constructor["__bjsmoduleName__"];
  9907. }
  9908. if (!className) {
  9909. className = typeof object;
  9910. }
  9911. }
  9912. if (!className) {
  9913. return null;
  9914. }
  9915. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9916. };
  9917. /**
  9918. * 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.
  9919. * @param array
  9920. */
  9921. Tools.arrayOrStringFeeder = function (array) {
  9922. return function (index) {
  9923. if (index >= array.length) {
  9924. return null;
  9925. }
  9926. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9927. if (val && val.getHashCode) {
  9928. val = val.getHashCode();
  9929. }
  9930. if (typeof val === "string") {
  9931. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9932. }
  9933. return val;
  9934. };
  9935. };
  9936. /**
  9937. * Compute the hashCode of a stream of number
  9938. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9939. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9940. * @return the hash code computed
  9941. */
  9942. Tools.hashCodeFromStream = function (feeder) {
  9943. // Based from here: http://stackoverflow.com/a/7616484/802124
  9944. var hash = 0;
  9945. var index = 0;
  9946. var chr = feeder(index++);
  9947. while (chr != null) {
  9948. hash = ((hash << 5) - hash) + chr;
  9949. hash |= 0; // Convert to 32bit integer
  9950. chr = feeder(index++);
  9951. }
  9952. return hash;
  9953. };
  9954. /**
  9955. * Returns a promise that resolves after the given amount of time.
  9956. * @param delay Number of milliseconds to delay
  9957. * @returns Promise that resolves after the given amount of time
  9958. */
  9959. Tools.DelayAsync = function (delay) {
  9960. return new Promise(function (resolve) {
  9961. setTimeout(function () {
  9962. resolve();
  9963. }, delay);
  9964. });
  9965. };
  9966. /**
  9967. * Gets the current gradient from an array of IValueGradient
  9968. * @param ratio defines the current ratio to get
  9969. * @param gradients defines the array of IValueGradient
  9970. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9971. */
  9972. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9973. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9974. var currentGradient = gradients[gradientIndex];
  9975. var nextGradient = gradients[gradientIndex + 1];
  9976. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9977. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9978. updateFunc(currentGradient, nextGradient, scale);
  9979. }
  9980. }
  9981. };
  9982. Tools.BaseUrl = "";
  9983. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9984. /**
  9985. * Default behaviour for cors in the application.
  9986. * It can be a string if the expected behavior is identical in the entire app.
  9987. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9988. */
  9989. Tools.CorsBehavior = "anonymous";
  9990. Tools.UseFallbackTexture = true;
  9991. /**
  9992. * Use this object to register external classes like custom textures or material
  9993. * to allow the laoders to instantiate them
  9994. */
  9995. Tools.RegisteredExternalClasses = {};
  9996. // Used in case of a texture loading problem
  9997. 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";
  9998. Tools._tmpFloatArray = new Float32Array(1);
  9999. Tools.PreprocessUrl = function (url) {
  10000. return url;
  10001. };
  10002. // Logs
  10003. Tools._NoneLogLevel = 0;
  10004. Tools._MessageLogLevel = 1;
  10005. Tools._WarningLogLevel = 2;
  10006. Tools._ErrorLogLevel = 4;
  10007. Tools._LogCache = "";
  10008. Tools.errorsCount = 0;
  10009. Tools.Log = Tools._LogEnabled;
  10010. Tools.Warn = Tools._WarnEnabled;
  10011. Tools.Error = Tools._ErrorEnabled;
  10012. // Performances
  10013. Tools._PerformanceNoneLogLevel = 0;
  10014. Tools._PerformanceUserMarkLogLevel = 1;
  10015. Tools._PerformanceConsoleLogLevel = 2;
  10016. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10017. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10018. return Tools;
  10019. }());
  10020. BABYLON.Tools = Tools;
  10021. /**
  10022. * This class is used to track a performance counter which is number based.
  10023. * The user has access to many properties which give statistics of different nature
  10024. *
  10025. * The implementer can track two kinds of Performance Counter: time and count
  10026. * 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.
  10027. * 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.
  10028. */
  10029. var PerfCounter = /** @class */ (function () {
  10030. function PerfCounter() {
  10031. this._startMonitoringTime = 0;
  10032. this._min = 0;
  10033. this._max = 0;
  10034. this._average = 0;
  10035. this._lastSecAverage = 0;
  10036. this._current = 0;
  10037. this._totalValueCount = 0;
  10038. this._totalAccumulated = 0;
  10039. this._lastSecAccumulated = 0;
  10040. this._lastSecTime = 0;
  10041. this._lastSecValueCount = 0;
  10042. }
  10043. Object.defineProperty(PerfCounter.prototype, "min", {
  10044. /**
  10045. * Returns the smallest value ever
  10046. */
  10047. get: function () {
  10048. return this._min;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(PerfCounter.prototype, "max", {
  10054. /**
  10055. * Returns the biggest value ever
  10056. */
  10057. get: function () {
  10058. return this._max;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(PerfCounter.prototype, "average", {
  10064. /**
  10065. * Returns the average value since the performance counter is running
  10066. */
  10067. get: function () {
  10068. return this._average;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10074. /**
  10075. * Returns the average value of the last second the counter was monitored
  10076. */
  10077. get: function () {
  10078. return this._lastSecAverage;
  10079. },
  10080. enumerable: true,
  10081. configurable: true
  10082. });
  10083. Object.defineProperty(PerfCounter.prototype, "current", {
  10084. /**
  10085. * Returns the current value
  10086. */
  10087. get: function () {
  10088. return this._current;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(PerfCounter.prototype, "total", {
  10094. get: function () {
  10095. return this._totalAccumulated;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(PerfCounter.prototype, "count", {
  10101. get: function () {
  10102. return this._totalValueCount;
  10103. },
  10104. enumerable: true,
  10105. configurable: true
  10106. });
  10107. /**
  10108. * Call this method to start monitoring a new frame.
  10109. * 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.
  10110. */
  10111. PerfCounter.prototype.fetchNewFrame = function () {
  10112. this._totalValueCount++;
  10113. this._current = 0;
  10114. this._lastSecValueCount++;
  10115. };
  10116. /**
  10117. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10118. * @param newCount the count value to add to the monitored count
  10119. * @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.
  10120. */
  10121. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10122. if (!PerfCounter.Enabled) {
  10123. return;
  10124. }
  10125. this._current += newCount;
  10126. if (fetchResult) {
  10127. this._fetchResult();
  10128. }
  10129. };
  10130. /**
  10131. * Start monitoring this performance counter
  10132. */
  10133. PerfCounter.prototype.beginMonitoring = function () {
  10134. if (!PerfCounter.Enabled) {
  10135. return;
  10136. }
  10137. this._startMonitoringTime = Tools.Now;
  10138. };
  10139. /**
  10140. * Compute the time lapsed since the previous beginMonitoring() call.
  10141. * @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
  10142. */
  10143. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10144. if (newFrame === void 0) { newFrame = true; }
  10145. if (!PerfCounter.Enabled) {
  10146. return;
  10147. }
  10148. if (newFrame) {
  10149. this.fetchNewFrame();
  10150. }
  10151. var currentTime = Tools.Now;
  10152. this._current = currentTime - this._startMonitoringTime;
  10153. if (newFrame) {
  10154. this._fetchResult();
  10155. }
  10156. };
  10157. PerfCounter.prototype._fetchResult = function () {
  10158. this._totalAccumulated += this._current;
  10159. this._lastSecAccumulated += this._current;
  10160. // Min/Max update
  10161. this._min = Math.min(this._min, this._current);
  10162. this._max = Math.max(this._max, this._current);
  10163. this._average = this._totalAccumulated / this._totalValueCount;
  10164. // Reset last sec?
  10165. var now = Tools.Now;
  10166. if ((now - this._lastSecTime) > 1000) {
  10167. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10168. this._lastSecTime = now;
  10169. this._lastSecAccumulated = 0;
  10170. this._lastSecValueCount = 0;
  10171. }
  10172. };
  10173. PerfCounter.Enabled = true;
  10174. return PerfCounter;
  10175. }());
  10176. BABYLON.PerfCounter = PerfCounter;
  10177. /**
  10178. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10179. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10180. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10181. * @param name The name of the class, case should be preserved
  10182. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10183. */
  10184. function className(name, module) {
  10185. return function (target) {
  10186. target["__bjsclassName__"] = name;
  10187. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10188. };
  10189. }
  10190. BABYLON.className = className;
  10191. /**
  10192. * An implementation of a loop for asynchronous functions.
  10193. */
  10194. var AsyncLoop = /** @class */ (function () {
  10195. /**
  10196. * Constroctor.
  10197. * @param iterations the number of iterations.
  10198. * @param _fn the function to run each iteration
  10199. * @param _successCallback the callback that will be called upon succesful execution
  10200. * @param offset starting offset.
  10201. */
  10202. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10203. if (offset === void 0) { offset = 0; }
  10204. this.iterations = iterations;
  10205. this._fn = _fn;
  10206. this._successCallback = _successCallback;
  10207. this.index = offset - 1;
  10208. this._done = false;
  10209. }
  10210. /**
  10211. * Execute the next iteration. Must be called after the last iteration was finished.
  10212. */
  10213. AsyncLoop.prototype.executeNext = function () {
  10214. if (!this._done) {
  10215. if (this.index + 1 < this.iterations) {
  10216. ++this.index;
  10217. this._fn(this);
  10218. }
  10219. else {
  10220. this.breakLoop();
  10221. }
  10222. }
  10223. };
  10224. /**
  10225. * Break the loop and run the success callback.
  10226. */
  10227. AsyncLoop.prototype.breakLoop = function () {
  10228. this._done = true;
  10229. this._successCallback();
  10230. };
  10231. /**
  10232. * Helper function
  10233. */
  10234. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10235. if (offset === void 0) { offset = 0; }
  10236. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10237. loop.executeNext();
  10238. return loop;
  10239. };
  10240. /**
  10241. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10242. * @param iterations total number of iterations
  10243. * @param syncedIterations number of synchronous iterations in each async iteration.
  10244. * @param fn the function to call each iteration.
  10245. * @param callback a success call back that will be called when iterating stops.
  10246. * @param breakFunction a break condition (optional)
  10247. * @param timeout timeout settings for the setTimeout function. default - 0.
  10248. * @constructor
  10249. */
  10250. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10251. if (timeout === void 0) { timeout = 0; }
  10252. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10253. if (breakFunction && breakFunction())
  10254. loop.breakLoop();
  10255. else {
  10256. setTimeout(function () {
  10257. for (var i = 0; i < syncedIterations; ++i) {
  10258. var iteration = (loop.index * syncedIterations) + i;
  10259. if (iteration >= iterations)
  10260. break;
  10261. fn(iteration);
  10262. if (breakFunction && breakFunction()) {
  10263. loop.breakLoop();
  10264. break;
  10265. }
  10266. }
  10267. loop.executeNext();
  10268. }, timeout);
  10269. }
  10270. }, callback);
  10271. };
  10272. return AsyncLoop;
  10273. }());
  10274. BABYLON.AsyncLoop = AsyncLoop;
  10275. })(BABYLON || (BABYLON = {}));
  10276. //# sourceMappingURL=babylon.tools.js.map
  10277. var BABYLON;
  10278. (function (BABYLON) {
  10279. var PromiseStates;
  10280. (function (PromiseStates) {
  10281. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10282. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10283. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10284. })(PromiseStates || (PromiseStates = {}));
  10285. var FulFillmentAgregator = /** @class */ (function () {
  10286. function FulFillmentAgregator() {
  10287. this.count = 0;
  10288. this.target = 0;
  10289. this.results = [];
  10290. }
  10291. return FulFillmentAgregator;
  10292. }());
  10293. var InternalPromise = /** @class */ (function () {
  10294. function InternalPromise(resolver) {
  10295. var _this = this;
  10296. this._state = PromiseStates.Pending;
  10297. this._children = new Array();
  10298. this._rejectWasConsumed = false;
  10299. if (!resolver) {
  10300. return;
  10301. }
  10302. try {
  10303. resolver(function (value) {
  10304. _this._resolve(value);
  10305. }, function (reason) {
  10306. _this._reject(reason);
  10307. });
  10308. }
  10309. catch (e) {
  10310. this._reject(e);
  10311. }
  10312. }
  10313. Object.defineProperty(InternalPromise.prototype, "_result", {
  10314. get: function () {
  10315. return this._resultValue;
  10316. },
  10317. set: function (value) {
  10318. this._resultValue = value;
  10319. if (this._parent && this._parent._result === undefined) {
  10320. this._parent._result = value;
  10321. }
  10322. },
  10323. enumerable: true,
  10324. configurable: true
  10325. });
  10326. InternalPromise.prototype.catch = function (onRejected) {
  10327. return this.then(undefined, onRejected);
  10328. };
  10329. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10330. var _this = this;
  10331. var newPromise = new InternalPromise();
  10332. newPromise._onFulfilled = onFulfilled;
  10333. newPromise._onRejected = onRejected;
  10334. // Composition
  10335. this._children.push(newPromise);
  10336. newPromise._parent = this;
  10337. if (this._state !== PromiseStates.Pending) {
  10338. BABYLON.Tools.SetImmediate(function () {
  10339. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10340. var returnedValue = newPromise._resolve(_this._result);
  10341. if (returnedValue !== undefined && returnedValue !== null) {
  10342. if (returnedValue._state !== undefined) {
  10343. var returnedPromise = returnedValue;
  10344. newPromise._children.push(returnedPromise);
  10345. returnedPromise._parent = newPromise;
  10346. newPromise = returnedPromise;
  10347. }
  10348. else {
  10349. newPromise._result = returnedValue;
  10350. }
  10351. }
  10352. }
  10353. else {
  10354. newPromise._reject(_this._reason);
  10355. }
  10356. });
  10357. }
  10358. return newPromise;
  10359. };
  10360. InternalPromise.prototype._moveChildren = function (children) {
  10361. var _this = this;
  10362. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10363. this._children.forEach(function (child) {
  10364. child._parent = _this;
  10365. });
  10366. if (this._state === PromiseStates.Fulfilled) {
  10367. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10368. var child = _b[_i];
  10369. child._resolve(this._result);
  10370. }
  10371. }
  10372. else if (this._state === PromiseStates.Rejected) {
  10373. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10374. var child = _d[_c];
  10375. child._reject(this._reason);
  10376. }
  10377. }
  10378. var _a;
  10379. };
  10380. InternalPromise.prototype._resolve = function (value) {
  10381. try {
  10382. this._state = PromiseStates.Fulfilled;
  10383. var returnedValue = null;
  10384. if (this._onFulfilled) {
  10385. returnedValue = this._onFulfilled(value);
  10386. }
  10387. if (returnedValue !== undefined && returnedValue !== null) {
  10388. if (returnedValue._state !== undefined) {
  10389. // Transmit children
  10390. var returnedPromise = returnedValue;
  10391. returnedPromise._parent = this;
  10392. returnedPromise._moveChildren(this._children);
  10393. value = returnedPromise._result;
  10394. }
  10395. else {
  10396. value = returnedValue;
  10397. }
  10398. }
  10399. this._result = value;
  10400. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10401. var child = _a[_i];
  10402. child._resolve(value);
  10403. }
  10404. this._children.length = 0;
  10405. delete this._onFulfilled;
  10406. delete this._onRejected;
  10407. }
  10408. catch (e) {
  10409. this._reject(e, true);
  10410. }
  10411. };
  10412. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10413. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10414. this._state = PromiseStates.Rejected;
  10415. this._reason = reason;
  10416. if (this._onRejected && !onLocalThrow) {
  10417. try {
  10418. this._onRejected(reason);
  10419. this._rejectWasConsumed = true;
  10420. }
  10421. catch (e) {
  10422. reason = e;
  10423. }
  10424. }
  10425. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10426. var child = _a[_i];
  10427. if (this._rejectWasConsumed) {
  10428. child._resolve(null);
  10429. }
  10430. else {
  10431. child._reject(reason);
  10432. }
  10433. }
  10434. this._children.length = 0;
  10435. delete this._onFulfilled;
  10436. delete this._onRejected;
  10437. };
  10438. InternalPromise.resolve = function (value) {
  10439. var newPromise = new InternalPromise();
  10440. newPromise._resolve(value);
  10441. return newPromise;
  10442. };
  10443. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10444. promise.then(function (value) {
  10445. agregator.results[index] = value;
  10446. agregator.count++;
  10447. if (agregator.count === agregator.target) {
  10448. agregator.rootPromise._resolve(agregator.results);
  10449. }
  10450. return null;
  10451. }, function (reason) {
  10452. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10453. agregator.rootPromise._reject(reason);
  10454. }
  10455. });
  10456. };
  10457. InternalPromise.all = function (promises) {
  10458. var newPromise = new InternalPromise();
  10459. var agregator = new FulFillmentAgregator();
  10460. agregator.target = promises.length;
  10461. agregator.rootPromise = newPromise;
  10462. if (promises.length) {
  10463. for (var index = 0; index < promises.length; index++) {
  10464. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10465. }
  10466. }
  10467. else {
  10468. newPromise._resolve([]);
  10469. }
  10470. return newPromise;
  10471. };
  10472. InternalPromise.race = function (promises) {
  10473. var newPromise = new InternalPromise();
  10474. if (promises.length) {
  10475. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10476. var promise = promises_1[_i];
  10477. promise.then(function (value) {
  10478. if (newPromise) {
  10479. newPromise._resolve(value);
  10480. newPromise = null;
  10481. }
  10482. return null;
  10483. }, function (reason) {
  10484. if (newPromise) {
  10485. newPromise._reject(reason);
  10486. newPromise = null;
  10487. }
  10488. });
  10489. }
  10490. }
  10491. return newPromise;
  10492. };
  10493. return InternalPromise;
  10494. }());
  10495. /**
  10496. * Helper class that provides a small promise polyfill
  10497. */
  10498. var PromisePolyfill = /** @class */ (function () {
  10499. function PromisePolyfill() {
  10500. }
  10501. /**
  10502. * Static function used to check if the polyfill is required
  10503. * If this is the case then the function will inject the polyfill to window.Promise
  10504. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10505. */
  10506. PromisePolyfill.Apply = function (force) {
  10507. if (force === void 0) { force = false; }
  10508. if (force || typeof Promise === 'undefined') {
  10509. var root = window;
  10510. root.Promise = InternalPromise;
  10511. }
  10512. };
  10513. return PromisePolyfill;
  10514. }());
  10515. BABYLON.PromisePolyfill = PromisePolyfill;
  10516. })(BABYLON || (BABYLON = {}));
  10517. //# sourceMappingURL=babylon.promise.js.map
  10518. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10519. var BABYLON;
  10520. (function (BABYLON) {
  10521. /**
  10522. * Helper class to push actions to a pool of workers.
  10523. */
  10524. var WorkerPool = /** @class */ (function () {
  10525. /**
  10526. * Constructor
  10527. * @param workers Array of workers to use for actions
  10528. */
  10529. function WorkerPool(workers) {
  10530. this._pendingActions = new Array();
  10531. this._workerInfos = workers.map(function (worker) { return ({
  10532. worker: worker,
  10533. active: false
  10534. }); });
  10535. }
  10536. /**
  10537. * Terminates all workers and clears any pending actions.
  10538. */
  10539. WorkerPool.prototype.dispose = function () {
  10540. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10541. var workerInfo = _a[_i];
  10542. workerInfo.worker.terminate();
  10543. }
  10544. delete this._workerInfos;
  10545. delete this._pendingActions;
  10546. };
  10547. /**
  10548. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10549. * pended until a worker has completed its action.
  10550. * @param action The action to perform. Call onComplete when the action is complete.
  10551. */
  10552. WorkerPool.prototype.push = function (action) {
  10553. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10554. var workerInfo = _a[_i];
  10555. if (!workerInfo.active) {
  10556. this._execute(workerInfo, action);
  10557. return;
  10558. }
  10559. }
  10560. this._pendingActions.push(action);
  10561. };
  10562. WorkerPool.prototype._execute = function (workerInfo, action) {
  10563. var _this = this;
  10564. workerInfo.active = true;
  10565. action(workerInfo.worker, function () {
  10566. workerInfo.active = false;
  10567. var nextAction = _this._pendingActions.shift();
  10568. if (nextAction) {
  10569. _this._execute(workerInfo, nextAction);
  10570. }
  10571. });
  10572. };
  10573. return WorkerPool;
  10574. }());
  10575. BABYLON.WorkerPool = WorkerPool;
  10576. })(BABYLON || (BABYLON = {}));
  10577. //# sourceMappingURL=babylon.workerPool.js.map
  10578. var BABYLON;
  10579. (function (BABYLON) {
  10580. /**
  10581. * @hidden
  10582. **/
  10583. var _AlphaState = /** @class */ (function () {
  10584. /**
  10585. * Initializes the state.
  10586. */
  10587. function _AlphaState() {
  10588. this._isAlphaBlendDirty = false;
  10589. this._isBlendFunctionParametersDirty = false;
  10590. this._isBlendEquationParametersDirty = false;
  10591. this._isBlendConstantsDirty = false;
  10592. this._alphaBlend = false;
  10593. this._blendFunctionParameters = new Array(4);
  10594. this._blendEquationParameters = new Array(2);
  10595. this._blendConstants = new Array(4);
  10596. this.reset();
  10597. }
  10598. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10599. get: function () {
  10600. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10601. },
  10602. enumerable: true,
  10603. configurable: true
  10604. });
  10605. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10606. get: function () {
  10607. return this._alphaBlend;
  10608. },
  10609. set: function (value) {
  10610. if (this._alphaBlend === value) {
  10611. return;
  10612. }
  10613. this._alphaBlend = value;
  10614. this._isAlphaBlendDirty = true;
  10615. },
  10616. enumerable: true,
  10617. configurable: true
  10618. });
  10619. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10620. if (this._blendConstants[0] === r &&
  10621. this._blendConstants[1] === g &&
  10622. this._blendConstants[2] === b &&
  10623. this._blendConstants[3] === a) {
  10624. return;
  10625. }
  10626. this._blendConstants[0] = r;
  10627. this._blendConstants[1] = g;
  10628. this._blendConstants[2] = b;
  10629. this._blendConstants[3] = a;
  10630. this._isBlendConstantsDirty = true;
  10631. };
  10632. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10633. if (this._blendFunctionParameters[0] === value0 &&
  10634. this._blendFunctionParameters[1] === value1 &&
  10635. this._blendFunctionParameters[2] === value2 &&
  10636. this._blendFunctionParameters[3] === value3) {
  10637. return;
  10638. }
  10639. this._blendFunctionParameters[0] = value0;
  10640. this._blendFunctionParameters[1] = value1;
  10641. this._blendFunctionParameters[2] = value2;
  10642. this._blendFunctionParameters[3] = value3;
  10643. this._isBlendFunctionParametersDirty = true;
  10644. };
  10645. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10646. if (this._blendEquationParameters[0] === rgb &&
  10647. this._blendEquationParameters[1] === alpha) {
  10648. return;
  10649. }
  10650. this._blendEquationParameters[0] = rgb;
  10651. this._blendEquationParameters[1] = alpha;
  10652. this._isBlendEquationParametersDirty = true;
  10653. };
  10654. _AlphaState.prototype.reset = function () {
  10655. this._alphaBlend = false;
  10656. this._blendFunctionParameters[0] = null;
  10657. this._blendFunctionParameters[1] = null;
  10658. this._blendFunctionParameters[2] = null;
  10659. this._blendFunctionParameters[3] = null;
  10660. this._blendEquationParameters[0] = null;
  10661. this._blendEquationParameters[1] = null;
  10662. this._blendConstants[0] = null;
  10663. this._blendConstants[1] = null;
  10664. this._blendConstants[2] = null;
  10665. this._blendConstants[3] = null;
  10666. this._isAlphaBlendDirty = true;
  10667. this._isBlendFunctionParametersDirty = false;
  10668. this._isBlendEquationParametersDirty = false;
  10669. this._isBlendConstantsDirty = false;
  10670. };
  10671. _AlphaState.prototype.apply = function (gl) {
  10672. if (!this.isDirty) {
  10673. return;
  10674. }
  10675. // Alpha blend
  10676. if (this._isAlphaBlendDirty) {
  10677. if (this._alphaBlend) {
  10678. gl.enable(gl.BLEND);
  10679. }
  10680. else {
  10681. gl.disable(gl.BLEND);
  10682. }
  10683. this._isAlphaBlendDirty = false;
  10684. }
  10685. // Alpha function
  10686. if (this._isBlendFunctionParametersDirty) {
  10687. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10688. this._isBlendFunctionParametersDirty = false;
  10689. }
  10690. // Alpha equation
  10691. if (this._isBlendEquationParametersDirty) {
  10692. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10693. this._isBlendEquationParametersDirty = false;
  10694. }
  10695. // Constants
  10696. if (this._isBlendConstantsDirty) {
  10697. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10698. this._isBlendConstantsDirty = false;
  10699. }
  10700. };
  10701. return _AlphaState;
  10702. }());
  10703. BABYLON._AlphaState = _AlphaState;
  10704. })(BABYLON || (BABYLON = {}));
  10705. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10706. var BABYLON;
  10707. (function (BABYLON) {
  10708. /**
  10709. * @hidden
  10710. **/
  10711. var _DepthCullingState = /** @class */ (function () {
  10712. /**
  10713. * Initializes the state.
  10714. */
  10715. function _DepthCullingState() {
  10716. this._isDepthTestDirty = false;
  10717. this._isDepthMaskDirty = false;
  10718. this._isDepthFuncDirty = false;
  10719. this._isCullFaceDirty = false;
  10720. this._isCullDirty = false;
  10721. this._isZOffsetDirty = false;
  10722. this._isFrontFaceDirty = false;
  10723. this.reset();
  10724. }
  10725. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10726. get: function () {
  10727. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10733. get: function () {
  10734. return this._zOffset;
  10735. },
  10736. set: function (value) {
  10737. if (this._zOffset === value) {
  10738. return;
  10739. }
  10740. this._zOffset = value;
  10741. this._isZOffsetDirty = true;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10747. get: function () {
  10748. return this._cullFace;
  10749. },
  10750. set: function (value) {
  10751. if (this._cullFace === value) {
  10752. return;
  10753. }
  10754. this._cullFace = value;
  10755. this._isCullFaceDirty = true;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10761. get: function () {
  10762. return this._cull;
  10763. },
  10764. set: function (value) {
  10765. if (this._cull === value) {
  10766. return;
  10767. }
  10768. this._cull = value;
  10769. this._isCullDirty = true;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10775. get: function () {
  10776. return this._depthFunc;
  10777. },
  10778. set: function (value) {
  10779. if (this._depthFunc === value) {
  10780. return;
  10781. }
  10782. this._depthFunc = value;
  10783. this._isDepthFuncDirty = true;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10789. get: function () {
  10790. return this._depthMask;
  10791. },
  10792. set: function (value) {
  10793. if (this._depthMask === value) {
  10794. return;
  10795. }
  10796. this._depthMask = value;
  10797. this._isDepthMaskDirty = true;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10803. get: function () {
  10804. return this._depthTest;
  10805. },
  10806. set: function (value) {
  10807. if (this._depthTest === value) {
  10808. return;
  10809. }
  10810. this._depthTest = value;
  10811. this._isDepthTestDirty = true;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10817. get: function () {
  10818. return this._frontFace;
  10819. },
  10820. set: function (value) {
  10821. if (this._frontFace === value) {
  10822. return;
  10823. }
  10824. this._frontFace = value;
  10825. this._isFrontFaceDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. _DepthCullingState.prototype.reset = function () {
  10831. this._depthMask = true;
  10832. this._depthTest = true;
  10833. this._depthFunc = null;
  10834. this._cullFace = null;
  10835. this._cull = null;
  10836. this._zOffset = 0;
  10837. this._frontFace = null;
  10838. this._isDepthTestDirty = true;
  10839. this._isDepthMaskDirty = true;
  10840. this._isDepthFuncDirty = false;
  10841. this._isCullFaceDirty = false;
  10842. this._isCullDirty = false;
  10843. this._isZOffsetDirty = false;
  10844. this._isFrontFaceDirty = false;
  10845. };
  10846. _DepthCullingState.prototype.apply = function (gl) {
  10847. if (!this.isDirty) {
  10848. return;
  10849. }
  10850. // Cull
  10851. if (this._isCullDirty) {
  10852. if (this.cull) {
  10853. gl.enable(gl.CULL_FACE);
  10854. }
  10855. else {
  10856. gl.disable(gl.CULL_FACE);
  10857. }
  10858. this._isCullDirty = false;
  10859. }
  10860. // Cull face
  10861. if (this._isCullFaceDirty) {
  10862. gl.cullFace(this.cullFace);
  10863. this._isCullFaceDirty = false;
  10864. }
  10865. // Depth mask
  10866. if (this._isDepthMaskDirty) {
  10867. gl.depthMask(this.depthMask);
  10868. this._isDepthMaskDirty = false;
  10869. }
  10870. // Depth test
  10871. if (this._isDepthTestDirty) {
  10872. if (this.depthTest) {
  10873. gl.enable(gl.DEPTH_TEST);
  10874. }
  10875. else {
  10876. gl.disable(gl.DEPTH_TEST);
  10877. }
  10878. this._isDepthTestDirty = false;
  10879. }
  10880. // Depth func
  10881. if (this._isDepthFuncDirty) {
  10882. gl.depthFunc(this.depthFunc);
  10883. this._isDepthFuncDirty = false;
  10884. }
  10885. // zOffset
  10886. if (this._isZOffsetDirty) {
  10887. if (this.zOffset) {
  10888. gl.enable(gl.POLYGON_OFFSET_FILL);
  10889. gl.polygonOffset(this.zOffset, 0);
  10890. }
  10891. else {
  10892. gl.disable(gl.POLYGON_OFFSET_FILL);
  10893. }
  10894. this._isZOffsetDirty = false;
  10895. }
  10896. // Front face
  10897. if (this._isFrontFaceDirty) {
  10898. gl.frontFace(this.frontFace);
  10899. this._isFrontFaceDirty = false;
  10900. }
  10901. };
  10902. return _DepthCullingState;
  10903. }());
  10904. BABYLON._DepthCullingState = _DepthCullingState;
  10905. })(BABYLON || (BABYLON = {}));
  10906. //# sourceMappingURL=babylon.depthCullingState.js.map
  10907. var BABYLON;
  10908. (function (BABYLON) {
  10909. /**
  10910. * @hidden
  10911. **/
  10912. var _StencilState = /** @class */ (function () {
  10913. function _StencilState() {
  10914. this._isStencilTestDirty = false;
  10915. this._isStencilMaskDirty = false;
  10916. this._isStencilFuncDirty = false;
  10917. this._isStencilOpDirty = false;
  10918. this.reset();
  10919. }
  10920. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10921. get: function () {
  10922. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10928. get: function () {
  10929. return this._stencilFunc;
  10930. },
  10931. set: function (value) {
  10932. if (this._stencilFunc === value) {
  10933. return;
  10934. }
  10935. this._stencilFunc = value;
  10936. this._isStencilFuncDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10942. get: function () {
  10943. return this._stencilFuncRef;
  10944. },
  10945. set: function (value) {
  10946. if (this._stencilFuncRef === value) {
  10947. return;
  10948. }
  10949. this._stencilFuncRef = value;
  10950. this._isStencilFuncDirty = true;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10956. get: function () {
  10957. return this._stencilFuncMask;
  10958. },
  10959. set: function (value) {
  10960. if (this._stencilFuncMask === value) {
  10961. return;
  10962. }
  10963. this._stencilFuncMask = value;
  10964. this._isStencilFuncDirty = true;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10970. get: function () {
  10971. return this._stencilOpStencilFail;
  10972. },
  10973. set: function (value) {
  10974. if (this._stencilOpStencilFail === value) {
  10975. return;
  10976. }
  10977. this._stencilOpStencilFail = value;
  10978. this._isStencilOpDirty = true;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10984. get: function () {
  10985. return this._stencilOpDepthFail;
  10986. },
  10987. set: function (value) {
  10988. if (this._stencilOpDepthFail === value) {
  10989. return;
  10990. }
  10991. this._stencilOpDepthFail = value;
  10992. this._isStencilOpDirty = true;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10998. get: function () {
  10999. return this._stencilOpStencilDepthPass;
  11000. },
  11001. set: function (value) {
  11002. if (this._stencilOpStencilDepthPass === value) {
  11003. return;
  11004. }
  11005. this._stencilOpStencilDepthPass = value;
  11006. this._isStencilOpDirty = true;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11012. get: function () {
  11013. return this._stencilMask;
  11014. },
  11015. set: function (value) {
  11016. if (this._stencilMask === value) {
  11017. return;
  11018. }
  11019. this._stencilMask = value;
  11020. this._isStencilMaskDirty = true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11026. get: function () {
  11027. return this._stencilTest;
  11028. },
  11029. set: function (value) {
  11030. if (this._stencilTest === value) {
  11031. return;
  11032. }
  11033. this._stencilTest = value;
  11034. this._isStencilTestDirty = true;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. _StencilState.prototype.reset = function () {
  11040. this._stencilTest = false;
  11041. this._stencilMask = 0xFF;
  11042. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11043. this._stencilFuncRef = 1;
  11044. this._stencilFuncMask = 0xFF;
  11045. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11046. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11047. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11048. this._isStencilTestDirty = true;
  11049. this._isStencilMaskDirty = true;
  11050. this._isStencilFuncDirty = true;
  11051. this._isStencilOpDirty = true;
  11052. };
  11053. _StencilState.prototype.apply = function (gl) {
  11054. if (!this.isDirty) {
  11055. return;
  11056. }
  11057. // Stencil test
  11058. if (this._isStencilTestDirty) {
  11059. if (this.stencilTest) {
  11060. gl.enable(gl.STENCIL_TEST);
  11061. }
  11062. else {
  11063. gl.disable(gl.STENCIL_TEST);
  11064. }
  11065. this._isStencilTestDirty = false;
  11066. }
  11067. // Stencil mask
  11068. if (this._isStencilMaskDirty) {
  11069. gl.stencilMask(this.stencilMask);
  11070. this._isStencilMaskDirty = false;
  11071. }
  11072. // Stencil func
  11073. if (this._isStencilFuncDirty) {
  11074. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11075. this._isStencilFuncDirty = false;
  11076. }
  11077. // Stencil op
  11078. if (this._isStencilOpDirty) {
  11079. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11080. this._isStencilOpDirty = false;
  11081. }
  11082. };
  11083. return _StencilState;
  11084. }());
  11085. BABYLON._StencilState = _StencilState;
  11086. })(BABYLON || (BABYLON = {}));
  11087. //# sourceMappingURL=babylon.stencilState.js.map
  11088. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11089. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11090. s = arguments[i];
  11091. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11092. t[p] = s[p];
  11093. }
  11094. return t;
  11095. };
  11096. var BABYLON;
  11097. (function (BABYLON) {
  11098. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11099. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11100. };
  11101. var compileRawShader = function (gl, source, type) {
  11102. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11103. gl.shaderSource(shader, source);
  11104. gl.compileShader(shader);
  11105. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11106. var log = gl.getShaderInfoLog(shader);
  11107. if (log) {
  11108. throw new Error(log);
  11109. }
  11110. }
  11111. if (!shader) {
  11112. throw new Error("Something went wrong while compile the shader.");
  11113. }
  11114. return shader;
  11115. };
  11116. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11117. var magFilter = gl.NEAREST;
  11118. var minFilter = gl.NEAREST;
  11119. switch (samplingMode) {
  11120. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11121. magFilter = gl.LINEAR;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11124. }
  11125. else {
  11126. minFilter = gl.LINEAR;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11130. magFilter = gl.LINEAR;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11133. }
  11134. else {
  11135. minFilter = gl.LINEAR;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11142. }
  11143. else {
  11144. minFilter = gl.NEAREST;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11148. magFilter = gl.NEAREST;
  11149. if (generateMipMaps) {
  11150. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11151. }
  11152. else {
  11153. minFilter = gl.NEAREST;
  11154. }
  11155. break;
  11156. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11157. magFilter = gl.NEAREST;
  11158. if (generateMipMaps) {
  11159. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11160. }
  11161. else {
  11162. minFilter = gl.LINEAR;
  11163. }
  11164. break;
  11165. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11166. magFilter = gl.NEAREST;
  11167. if (generateMipMaps) {
  11168. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11169. }
  11170. else {
  11171. minFilter = gl.LINEAR;
  11172. }
  11173. break;
  11174. case BABYLON.Texture.NEAREST_LINEAR:
  11175. magFilter = gl.NEAREST;
  11176. minFilter = gl.LINEAR;
  11177. break;
  11178. case BABYLON.Texture.NEAREST_NEAREST:
  11179. magFilter = gl.NEAREST;
  11180. minFilter = gl.NEAREST;
  11181. break;
  11182. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11183. magFilter = gl.LINEAR;
  11184. if (generateMipMaps) {
  11185. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11186. }
  11187. else {
  11188. minFilter = gl.NEAREST;
  11189. }
  11190. break;
  11191. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11192. magFilter = gl.LINEAR;
  11193. if (generateMipMaps) {
  11194. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11195. }
  11196. else {
  11197. minFilter = gl.NEAREST;
  11198. }
  11199. break;
  11200. case BABYLON.Texture.LINEAR_LINEAR:
  11201. magFilter = gl.LINEAR;
  11202. minFilter = gl.LINEAR;
  11203. break;
  11204. case BABYLON.Texture.LINEAR_NEAREST:
  11205. magFilter = gl.LINEAR;
  11206. minFilter = gl.NEAREST;
  11207. break;
  11208. }
  11209. return {
  11210. min: minFilter,
  11211. mag: magFilter
  11212. };
  11213. };
  11214. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11215. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11216. var img;
  11217. var onload = function () {
  11218. loadedImages[index] = img;
  11219. loadedImages._internalCount++;
  11220. if (scene) {
  11221. scene._removePendingData(img);
  11222. }
  11223. if (loadedImages._internalCount === 6) {
  11224. onfinish(loadedImages);
  11225. }
  11226. };
  11227. var onerror = function (message, exception) {
  11228. if (scene) {
  11229. scene._removePendingData(img);
  11230. }
  11231. if (onErrorCallBack) {
  11232. onErrorCallBack(message, exception);
  11233. }
  11234. };
  11235. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11236. if (scene) {
  11237. scene._addPendingData(img);
  11238. }
  11239. };
  11240. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11241. if (onError === void 0) { onError = null; }
  11242. var loadedImages = [];
  11243. loadedImages._internalCount = 0;
  11244. for (var index = 0; index < 6; index++) {
  11245. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11246. }
  11247. };
  11248. var BufferPointer = /** @class */ (function () {
  11249. function BufferPointer() {
  11250. }
  11251. return BufferPointer;
  11252. }());
  11253. /**
  11254. * Interface for attribute information associated with buffer instanciation
  11255. */
  11256. var InstancingAttributeInfo = /** @class */ (function () {
  11257. function InstancingAttributeInfo() {
  11258. }
  11259. return InstancingAttributeInfo;
  11260. }());
  11261. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11262. /**
  11263. * Define options used to create a render target texture
  11264. */
  11265. var RenderTargetCreationOptions = /** @class */ (function () {
  11266. function RenderTargetCreationOptions() {
  11267. }
  11268. return RenderTargetCreationOptions;
  11269. }());
  11270. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11271. /**
  11272. * Define options used to create a depth texture
  11273. */
  11274. var DepthTextureCreationOptions = /** @class */ (function () {
  11275. function DepthTextureCreationOptions() {
  11276. }
  11277. return DepthTextureCreationOptions;
  11278. }());
  11279. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11280. /**
  11281. * Class used to describe the capabilities of the engine relatively to the current browser
  11282. */
  11283. var EngineCapabilities = /** @class */ (function () {
  11284. function EngineCapabilities() {
  11285. }
  11286. return EngineCapabilities;
  11287. }());
  11288. BABYLON.EngineCapabilities = EngineCapabilities;
  11289. /**
  11290. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11291. */
  11292. var Engine = /** @class */ (function () {
  11293. /**
  11294. * Creates a new engine
  11295. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11296. * @param antialias defines enable antialiasing (default: false)
  11297. * @param options defines further options to be sent to the getContext() function
  11298. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11299. */
  11300. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11301. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11302. var _this = this;
  11303. // Public members
  11304. /**
  11305. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11306. */
  11307. this.forcePOTTextures = false;
  11308. /**
  11309. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11310. */
  11311. this.isFullscreen = false;
  11312. /**
  11313. * Gets a boolean indicating if the pointer is currently locked
  11314. */
  11315. this.isPointerLock = false;
  11316. /**
  11317. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11318. */
  11319. this.cullBackFaces = true;
  11320. /**
  11321. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11322. */
  11323. this.renderEvenInBackground = true;
  11324. /**
  11325. * Gets or sets a boolean indicating that cache can be kept between frames
  11326. */
  11327. this.preventCacheWipeBetweenFrames = false;
  11328. /**
  11329. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11330. **/
  11331. this.enableOfflineSupport = false;
  11332. /**
  11333. * 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)
  11334. **/
  11335. this.disableManifestCheck = false;
  11336. /**
  11337. * Gets the list of created scenes
  11338. */
  11339. this.scenes = new Array();
  11340. /**
  11341. * Gets the list of created postprocesses
  11342. */
  11343. this.postProcesses = new Array();
  11344. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11345. this.validateShaderPrograms = false;
  11346. // Observables
  11347. /**
  11348. * Observable event triggered each time the rendering canvas is resized
  11349. */
  11350. this.onResizeObservable = new BABYLON.Observable();
  11351. /**
  11352. * Observable event triggered each time the canvas loses focus
  11353. */
  11354. this.onCanvasBlurObservable = new BABYLON.Observable();
  11355. /**
  11356. * Observable event triggered each time the canvas gains focus
  11357. */
  11358. this.onCanvasFocusObservable = new BABYLON.Observable();
  11359. /**
  11360. * Observable event triggered each time the canvas receives pointerout event
  11361. */
  11362. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11363. /**
  11364. * Observable event triggered before each texture is initialized
  11365. */
  11366. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11367. //WebVR
  11368. this._vrDisplay = undefined;
  11369. this._vrSupported = false;
  11370. this._vrExclusivePointerMode = false;
  11371. // Uniform buffers list
  11372. /**
  11373. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11374. */
  11375. this.disableUniformBuffers = false;
  11376. /** @hidden */
  11377. this._uniformBuffers = new Array();
  11378. // Observables
  11379. /**
  11380. * Observable raised when the engine begins a new frame
  11381. */
  11382. this.onBeginFrameObservable = new BABYLON.Observable();
  11383. /**
  11384. * Observable raised when the engine ends the current frame
  11385. */
  11386. this.onEndFrameObservable = new BABYLON.Observable();
  11387. /**
  11388. * Observable raised when the engine is about to compile a shader
  11389. */
  11390. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11391. /**
  11392. * Observable raised when the engine has jsut compiled a shader
  11393. */
  11394. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11395. this._windowIsBackground = false;
  11396. this._webGLVersion = 1.0;
  11397. /** @hidden */
  11398. this._badOS = false;
  11399. /** @hidden */
  11400. this._badDesktopOS = false;
  11401. /**
  11402. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11403. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11404. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11405. */
  11406. this.disableTextureBindingOptimization = false;
  11407. /**
  11408. * Observable signaled when VR display mode changes
  11409. */
  11410. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11411. /**
  11412. * Observable signaled when VR request present is complete
  11413. */
  11414. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11415. /**
  11416. * Observable signaled when VR request present starts
  11417. */
  11418. this.onVRRequestPresentStart = new BABYLON.Observable();
  11419. this._colorWrite = true;
  11420. /** @hidden */
  11421. this._drawCalls = new BABYLON.PerfCounter();
  11422. /** @hidden */
  11423. this._textureCollisions = new BABYLON.PerfCounter();
  11424. this._renderingQueueLaunched = false;
  11425. this._activeRenderLoops = new Array();
  11426. // Deterministic lockstepMaxSteps
  11427. this._deterministicLockstep = false;
  11428. this._lockstepMaxSteps = 4;
  11429. // Lost context
  11430. /**
  11431. * Observable signaled when a context lost event is raised
  11432. */
  11433. this.onContextLostObservable = new BABYLON.Observable();
  11434. /**
  11435. * Observable signaled when a context restored event is raised
  11436. */
  11437. this.onContextRestoredObservable = new BABYLON.Observable();
  11438. this._contextWasLost = false;
  11439. this._doNotHandleContextLost = false;
  11440. // FPS
  11441. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11442. this._fps = 60;
  11443. this._deltaTime = 0;
  11444. /**
  11445. * Turn this value on if you want to pause FPS computation when in background
  11446. */
  11447. this.disablePerformanceMonitorInBackground = false;
  11448. // States
  11449. /** @hidden */
  11450. this._depthCullingState = new BABYLON._DepthCullingState();
  11451. /** @hidden */
  11452. this._stencilState = new BABYLON._StencilState();
  11453. /** @hidden */
  11454. this._alphaState = new BABYLON._AlphaState();
  11455. /** @hidden */
  11456. this._alphaMode = Engine.ALPHA_DISABLE;
  11457. // Cache
  11458. this._internalTexturesCache = new Array();
  11459. /** @hidden */
  11460. this._activeChannel = 0;
  11461. this._currentTextureChannel = -1;
  11462. /** @hidden */
  11463. this._boundTexturesCache = {};
  11464. this._compiledEffects = {};
  11465. this._vertexAttribArraysEnabled = [];
  11466. this._uintIndicesCurrentlySet = false;
  11467. this._currentBoundBuffer = new Array();
  11468. /** @hidden */
  11469. this._currentFramebuffer = null;
  11470. this._currentBufferPointers = new Array();
  11471. this._currentInstanceLocations = new Array();
  11472. this._currentInstanceBuffers = new Array();
  11473. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11474. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11475. this._vaoRecordInProgress = false;
  11476. this._mustWipeVertexAttributes = false;
  11477. this._nextFreeTextureSlots = new Array();
  11478. this._maxSimultaneousTextures = 0;
  11479. this._activeRequests = new Array();
  11480. // Hardware supported Compressed Textures
  11481. this._texturesSupported = new Array();
  11482. /**
  11483. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11484. */
  11485. this.premultipliedAlpha = true;
  11486. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11487. this._onVRFullScreenTriggered = function () {
  11488. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11489. //get the old size before we change
  11490. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11491. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11492. //get the width and height, change the render size
  11493. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11494. _this.setHardwareScalingLevel(1);
  11495. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11496. }
  11497. else {
  11498. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11499. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11500. }
  11501. };
  11502. this._unpackFlipYCached = null;
  11503. this._boundUniforms = {};
  11504. // Register promises
  11505. BABYLON.PromisePolyfill.Apply();
  11506. var canvas = null;
  11507. Engine.Instances.push(this);
  11508. if (!canvasOrContext) {
  11509. return;
  11510. }
  11511. options = options || {};
  11512. if (canvasOrContext.getContext) {
  11513. canvas = canvasOrContext;
  11514. this._renderingCanvas = canvas;
  11515. if (antialias != null) {
  11516. options.antialias = antialias;
  11517. }
  11518. if (options.deterministicLockstep === undefined) {
  11519. options.deterministicLockstep = false;
  11520. }
  11521. if (options.lockstepMaxSteps === undefined) {
  11522. options.lockstepMaxSteps = 4;
  11523. }
  11524. if (options.preserveDrawingBuffer === undefined) {
  11525. options.preserveDrawingBuffer = false;
  11526. }
  11527. if (options.audioEngine === undefined) {
  11528. options.audioEngine = true;
  11529. }
  11530. if (options.stencil === undefined) {
  11531. options.stencil = true;
  11532. }
  11533. if (options.premultipliedAlpha === false) {
  11534. this.premultipliedAlpha = false;
  11535. }
  11536. this._deterministicLockstep = options.deterministicLockstep;
  11537. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11538. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11539. // Exceptions
  11540. if (navigator && navigator.userAgent) {
  11541. var ua = navigator.userAgent;
  11542. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11543. var exception = _a[_i];
  11544. var key = exception.key;
  11545. var targets = exception.targets;
  11546. if (ua.indexOf(key) > -1) {
  11547. if (exception.capture && exception.captureConstraint) {
  11548. var capture = exception.capture;
  11549. var constraint = exception.captureConstraint;
  11550. var regex = new RegExp(capture);
  11551. var matches = regex.exec(ua);
  11552. if (matches && matches.length > 0) {
  11553. var capturedValue = parseInt(matches[matches.length - 1]);
  11554. if (capturedValue >= constraint) {
  11555. continue;
  11556. }
  11557. }
  11558. }
  11559. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11560. var target = targets_1[_b];
  11561. switch (target) {
  11562. case "uniformBuffer":
  11563. this.disableUniformBuffers = true;
  11564. break;
  11565. case "textureBindingOptimization":
  11566. this.disableTextureBindingOptimization = true;
  11567. break;
  11568. }
  11569. }
  11570. }
  11571. }
  11572. }
  11573. // GL
  11574. if (!options.disableWebGL2Support) {
  11575. try {
  11576. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11577. if (this._gl) {
  11578. this._webGLVersion = 2.0;
  11579. }
  11580. }
  11581. catch (e) {
  11582. // Do nothing
  11583. }
  11584. }
  11585. if (!this._gl) {
  11586. if (!canvas) {
  11587. throw new Error("The provided canvas is null or undefined.");
  11588. }
  11589. try {
  11590. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11591. }
  11592. catch (e) {
  11593. throw new Error("WebGL not supported");
  11594. }
  11595. }
  11596. if (!this._gl) {
  11597. throw new Error("WebGL not supported");
  11598. }
  11599. this._onCanvasFocus = function () {
  11600. _this.onCanvasFocusObservable.notifyObservers(_this);
  11601. };
  11602. this._onCanvasBlur = function () {
  11603. _this.onCanvasBlurObservable.notifyObservers(_this);
  11604. };
  11605. canvas.addEventListener("focus", this._onCanvasFocus);
  11606. canvas.addEventListener("blur", this._onCanvasBlur);
  11607. this._onBlur = function () {
  11608. if (_this.disablePerformanceMonitorInBackground) {
  11609. _this._performanceMonitor.disable();
  11610. }
  11611. _this._windowIsBackground = true;
  11612. };
  11613. this._onFocus = function () {
  11614. if (_this.disablePerformanceMonitorInBackground) {
  11615. _this._performanceMonitor.enable();
  11616. }
  11617. _this._windowIsBackground = false;
  11618. };
  11619. this._onCanvasPointerOut = function (ev) {
  11620. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11621. };
  11622. window.addEventListener("blur", this._onBlur);
  11623. window.addEventListener("focus", this._onFocus);
  11624. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11625. // Context lost
  11626. if (!this._doNotHandleContextLost) {
  11627. this._onContextLost = function (evt) {
  11628. evt.preventDefault();
  11629. _this._contextWasLost = true;
  11630. BABYLON.Tools.Warn("WebGL context lost.");
  11631. _this.onContextLostObservable.notifyObservers(_this);
  11632. };
  11633. this._onContextRestored = function (evt) {
  11634. // Adding a timeout to avoid race condition at browser level
  11635. setTimeout(function () {
  11636. // Rebuild gl context
  11637. _this._initGLContext();
  11638. // Rebuild effects
  11639. _this._rebuildEffects();
  11640. // Rebuild textures
  11641. _this._rebuildInternalTextures();
  11642. // Rebuild buffers
  11643. _this._rebuildBuffers();
  11644. // Cache
  11645. _this.wipeCaches(true);
  11646. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11647. _this.onContextRestoredObservable.notifyObservers(_this);
  11648. _this._contextWasLost = false;
  11649. }, 0);
  11650. };
  11651. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11652. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11653. }
  11654. }
  11655. else {
  11656. this._gl = canvasOrContext;
  11657. this._renderingCanvas = this._gl.canvas;
  11658. if (this._gl.renderbufferStorageMultisample) {
  11659. this._webGLVersion = 2.0;
  11660. }
  11661. options.stencil = this._gl.getContextAttributes().stencil;
  11662. }
  11663. // Viewport
  11664. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11665. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11666. this.resize();
  11667. this._isStencilEnable = options.stencil ? true : false;
  11668. this._initGLContext();
  11669. if (canvas) {
  11670. // Fullscreen
  11671. this._onFullscreenChange = function () {
  11672. if (document.fullscreen !== undefined) {
  11673. _this.isFullscreen = document.fullscreen;
  11674. }
  11675. else if (document.mozFullScreen !== undefined) {
  11676. _this.isFullscreen = document.mozFullScreen;
  11677. }
  11678. else if (document.webkitIsFullScreen !== undefined) {
  11679. _this.isFullscreen = document.webkitIsFullScreen;
  11680. }
  11681. else if (document.msIsFullScreen !== undefined) {
  11682. _this.isFullscreen = document.msIsFullScreen;
  11683. }
  11684. // Pointer lock
  11685. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11686. canvas.requestPointerLock = canvas.requestPointerLock ||
  11687. canvas.msRequestPointerLock ||
  11688. canvas.mozRequestPointerLock ||
  11689. canvas.webkitRequestPointerLock;
  11690. if (canvas.requestPointerLock) {
  11691. canvas.requestPointerLock();
  11692. }
  11693. }
  11694. };
  11695. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11696. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11697. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11698. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11699. // Pointer lock
  11700. this._onPointerLockChange = function () {
  11701. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11702. document.webkitPointerLockElement === canvas ||
  11703. document.msPointerLockElement === canvas ||
  11704. document.pointerLockElement === canvas);
  11705. };
  11706. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11707. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11708. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11709. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11710. this._onVRDisplayPointerRestricted = function () {
  11711. if (canvas) {
  11712. canvas.requestPointerLock();
  11713. }
  11714. };
  11715. this._onVRDisplayPointerUnrestricted = function () {
  11716. document.exitPointerLock();
  11717. };
  11718. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11719. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11720. }
  11721. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11722. Engine.audioEngine = new BABYLON.AudioEngine();
  11723. }
  11724. // Prepare buffer pointers
  11725. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11726. this._currentBufferPointers[i] = new BufferPointer();
  11727. }
  11728. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11729. // Load WebVR Devices
  11730. if (options.autoEnableWebVR) {
  11731. this.initWebVR();
  11732. }
  11733. // Detect if we are running on a faulty buggy OS.
  11734. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11735. // Detect if we are running on a faulty buggy desktop OS.
  11736. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11737. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11738. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11739. }
  11740. Object.defineProperty(Engine, "LastCreatedEngine", {
  11741. /**
  11742. * Gets the latest created engine
  11743. */
  11744. get: function () {
  11745. if (Engine.Instances.length === 0) {
  11746. return null;
  11747. }
  11748. return Engine.Instances[Engine.Instances.length - 1];
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "LastCreatedScene", {
  11754. /**
  11755. * Gets the latest created scene
  11756. */
  11757. get: function () {
  11758. var lastCreatedEngine = Engine.LastCreatedEngine;
  11759. if (!lastCreatedEngine) {
  11760. return null;
  11761. }
  11762. if (lastCreatedEngine.scenes.length === 0) {
  11763. return null;
  11764. }
  11765. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. /**
  11771. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11772. * @param flag defines which part of the materials must be marked as dirty
  11773. * @param predicate defines a predicate used to filter which materials should be affected
  11774. */
  11775. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11776. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11777. var engine = Engine.Instances[engineIndex];
  11778. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11779. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11780. }
  11781. }
  11782. };
  11783. Object.defineProperty(Engine, "NEVER", {
  11784. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11785. get: function () {
  11786. return Engine._NEVER;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine, "ALWAYS", {
  11792. /** 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 */
  11793. get: function () {
  11794. return Engine._ALWAYS;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine, "LESS", {
  11800. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11801. get: function () {
  11802. return Engine._LESS;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine, "EQUAL", {
  11808. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11809. get: function () {
  11810. return Engine._EQUAL;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "LEQUAL", {
  11816. /** 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 */
  11817. get: function () {
  11818. return Engine._LEQUAL;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "GREATER", {
  11824. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11825. get: function () {
  11826. return Engine._GREATER;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "GEQUAL", {
  11832. /** 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 */
  11833. get: function () {
  11834. return Engine._GEQUAL;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "NOTEQUAL", {
  11840. /** 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 */
  11841. get: function () {
  11842. return Engine._NOTEQUAL;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "KEEP", {
  11848. /** Passed to stencilOperation to specify that stencil value must be kept */
  11849. get: function () {
  11850. return Engine._KEEP;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "REPLACE", {
  11856. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11857. get: function () {
  11858. return Engine._REPLACE;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine, "INCR", {
  11864. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11865. get: function () {
  11866. return Engine._INCR;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(Engine, "DECR", {
  11872. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11873. get: function () {
  11874. return Engine._DECR;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine, "INVERT", {
  11880. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11881. get: function () {
  11882. return Engine._INVERT;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine, "INCR_WRAP", {
  11888. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11889. get: function () {
  11890. return Engine._INCR_WRAP;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "DECR_WRAP", {
  11896. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11897. get: function () {
  11898. return Engine._DECR_WRAP;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11904. // Alpha
  11905. /** Defines that alpha blending is disabled */
  11906. get: function () {
  11907. return Engine._ALPHA_DISABLE;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11913. /** Defines that alpha blending to SRC + DEST */
  11914. get: function () {
  11915. return Engine._ALPHA_ONEONE;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "ALPHA_ADD", {
  11921. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11922. get: function () {
  11923. return Engine._ALPHA_ADD;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11929. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11930. get: function () {
  11931. return Engine._ALPHA_COMBINE;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11937. /** Defines that alpha blending to DEST - SRC * DEST */
  11938. get: function () {
  11939. return Engine._ALPHA_SUBTRACT;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11945. /** Defines that alpha blending to SRC * DEST */
  11946. get: function () {
  11947. return Engine._ALPHA_MULTIPLY;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11953. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11954. get: function () {
  11955. return Engine._ALPHA_MAXIMIZED;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11961. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11962. get: function () {
  11963. return Engine._ALPHA_PREMULTIPLIED;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11969. /**
  11970. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11971. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11972. */
  11973. get: function () {
  11974. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11980. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11981. get: function () {
  11982. return Engine._ALPHA_INTERPOLATE;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11988. /**
  11989. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11990. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11991. */
  11992. get: function () {
  11993. return Engine._ALPHA_SCREENMODE;
  11994. },
  11995. enumerable: true,
  11996. configurable: true
  11997. });
  11998. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11999. // Delays
  12000. /** Defines that the ressource is not delayed*/
  12001. get: function () {
  12002. return Engine._DELAYLOADSTATE_NONE;
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  12008. /** Defines that the ressource was successfully delay loaded */
  12009. get: function () {
  12010. return Engine._DELAYLOADSTATE_LOADED;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12016. /** Defines that the ressource is currently delay loading */
  12017. get: function () {
  12018. return Engine._DELAYLOADSTATE_LOADING;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12024. /** Defines that the ressource is delayed and has not started loading */
  12025. get: function () {
  12026. return Engine._DELAYLOADSTATE_NOTLOADED;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12032. /** ALPHA */
  12033. get: function () {
  12034. return Engine._TEXTUREFORMAT_ALPHA;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12040. /** LUMINANCE */
  12041. get: function () {
  12042. return Engine._TEXTUREFORMAT_LUMINANCE;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12048. /**
  12049. * R
  12050. */
  12051. get: function () {
  12052. return Engine._TEXTUREFORMAT_R;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12058. /**
  12059. * RG
  12060. */
  12061. get: function () {
  12062. return Engine._TEXTUREFORMAT_RG;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12068. /** LUMINANCE_ALPHA */
  12069. get: function () {
  12070. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12076. /** RGB */
  12077. get: function () {
  12078. return Engine._TEXTUREFORMAT_RGB;
  12079. },
  12080. enumerable: true,
  12081. configurable: true
  12082. });
  12083. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12084. /** RGBA */
  12085. get: function () {
  12086. return Engine._TEXTUREFORMAT_RGBA;
  12087. },
  12088. enumerable: true,
  12089. configurable: true
  12090. });
  12091. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12092. /** UNSIGNED_INT */
  12093. get: function () {
  12094. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12100. /** FLOAT */
  12101. get: function () {
  12102. return Engine._TEXTURETYPE_FLOAT;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12108. /** HALF_FLOAT */
  12109. get: function () {
  12110. return Engine._TEXTURETYPE_HALF_FLOAT;
  12111. },
  12112. enumerable: true,
  12113. configurable: true
  12114. });
  12115. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12116. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12117. get: function () {
  12118. return Engine._SCALEMODE_FLOOR;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12124. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12125. get: function () {
  12126. return Engine._SCALEMODE_NEAREST;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12132. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12133. get: function () {
  12134. return Engine._SCALEMODE_CEILING;
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. Object.defineProperty(Engine, "Version", {
  12140. /**
  12141. * Returns the current version of the framework
  12142. */
  12143. get: function () {
  12144. return "3.3.0-alpha.9";
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12150. /**
  12151. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12152. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12153. */
  12154. get: function () {
  12155. return this._vrExclusivePointerMode;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12161. /**
  12162. * Gets a boolean indicating that the engine supports uniform buffers
  12163. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12164. */
  12165. get: function () {
  12166. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12172. /**
  12173. * Gets a boolean indicating that only power of 2 textures are supported
  12174. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12175. */
  12176. get: function () {
  12177. return this._webGLVersion < 2 || this.forcePOTTextures;
  12178. },
  12179. enumerable: true,
  12180. configurable: true
  12181. });
  12182. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12183. /**
  12184. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12185. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12186. */
  12187. get: function () {
  12188. return this._doNotHandleContextLost;
  12189. },
  12190. set: function (value) {
  12191. this._doNotHandleContextLost = value;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12197. /**
  12198. * Gets the performance monitor attached to this engine
  12199. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12200. */
  12201. get: function () {
  12202. return this._performanceMonitor;
  12203. },
  12204. enumerable: true,
  12205. configurable: true
  12206. });
  12207. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12208. /**
  12209. * Gets the list of texture formats supported
  12210. */
  12211. get: function () {
  12212. return this._texturesSupported;
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12218. /**
  12219. * Gets the list of texture formats in use
  12220. */
  12221. get: function () {
  12222. return this._textureFormatInUse;
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(Engine.prototype, "currentViewport", {
  12228. /**
  12229. * Gets the current viewport
  12230. */
  12231. get: function () {
  12232. return this._cachedViewport;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12238. /**
  12239. * Gets the default empty texture
  12240. */
  12241. get: function () {
  12242. if (!this._emptyTexture) {
  12243. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12244. }
  12245. return this._emptyTexture;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12251. /**
  12252. * Gets the default empty 3D texture
  12253. */
  12254. get: function () {
  12255. if (!this._emptyTexture3D) {
  12256. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12257. }
  12258. return this._emptyTexture3D;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12264. /**
  12265. * Gets the default empty cube texture
  12266. */
  12267. get: function () {
  12268. if (!this._emptyCubeTexture) {
  12269. var faceData = new Uint8Array(4);
  12270. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12271. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12272. }
  12273. return this._emptyCubeTexture;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Engine.prototype._rebuildInternalTextures = function () {
  12279. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12280. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12281. var internalTexture = currentState_1[_i];
  12282. internalTexture._rebuild();
  12283. }
  12284. };
  12285. Engine.prototype._rebuildEffects = function () {
  12286. for (var key in this._compiledEffects) {
  12287. var effect = this._compiledEffects[key];
  12288. effect._prepareEffect();
  12289. }
  12290. BABYLON.Effect.ResetCache();
  12291. };
  12292. Engine.prototype._rebuildBuffers = function () {
  12293. // Index / Vertex
  12294. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12295. var scene = _a[_i];
  12296. scene.resetCachedMaterial();
  12297. scene._rebuildGeometries();
  12298. scene._rebuildTextures();
  12299. }
  12300. // Uniforms
  12301. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12302. var uniformBuffer = _c[_b];
  12303. uniformBuffer._rebuild();
  12304. }
  12305. };
  12306. Engine.prototype._initGLContext = function () {
  12307. // Caps
  12308. this._caps = new EngineCapabilities();
  12309. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12310. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12311. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12312. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12313. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12314. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12315. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12316. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12317. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12318. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12319. // Infos
  12320. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12321. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12322. if (rendererInfo != null) {
  12323. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12324. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12325. }
  12326. if (!this._glVendor) {
  12327. this._glVendor = "Unknown vendor";
  12328. }
  12329. if (!this._glRenderer) {
  12330. this._glRenderer = "Unknown renderer";
  12331. }
  12332. // Constants
  12333. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12334. if (this._gl.RGBA16F !== 0x881A) {
  12335. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12336. }
  12337. if (this._gl.RGBA32F !== 0x8814) {
  12338. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12339. }
  12340. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12341. this._gl.DEPTH24_STENCIL8 = 35056;
  12342. }
  12343. // Extensions
  12344. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12345. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12346. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12347. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12348. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12349. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12350. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12351. 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');
  12352. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12353. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12354. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12355. this._caps.highPrecisionShaderSupported = true;
  12356. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12357. if (this._caps.timerQuery) {
  12358. if (this._webGLVersion === 1) {
  12359. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12360. }
  12361. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12362. }
  12363. // Checks if some of the format renders first to allow the use of webgl inspector.
  12364. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12365. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12366. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12367. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12368. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12369. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12370. if (this._webGLVersion > 1) {
  12371. this._gl.HALF_FLOAT_OES = 0x140B;
  12372. }
  12373. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12374. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12375. // Draw buffers
  12376. if (this._webGLVersion > 1) {
  12377. this._caps.drawBuffersExtension = true;
  12378. }
  12379. else {
  12380. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12381. if (drawBuffersExtension !== null) {
  12382. this._caps.drawBuffersExtension = true;
  12383. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12384. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12385. for (var i = 0; i < 16; i++) {
  12386. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12387. }
  12388. }
  12389. else {
  12390. this._caps.drawBuffersExtension = false;
  12391. }
  12392. }
  12393. // Depth Texture
  12394. if (this._webGLVersion > 1) {
  12395. this._caps.depthTextureExtension = true;
  12396. }
  12397. else {
  12398. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12399. if (depthTextureExtension != null) {
  12400. this._caps.depthTextureExtension = true;
  12401. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12402. }
  12403. }
  12404. // Vertex array object
  12405. if (this._webGLVersion > 1) {
  12406. this._caps.vertexArrayObject = true;
  12407. }
  12408. else {
  12409. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12410. if (vertexArrayObjectExtension != null) {
  12411. this._caps.vertexArrayObject = true;
  12412. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12413. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12414. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12415. }
  12416. else {
  12417. this._caps.vertexArrayObject = false;
  12418. }
  12419. }
  12420. // Instances count
  12421. if (this._webGLVersion > 1) {
  12422. this._caps.instancedArrays = true;
  12423. }
  12424. else {
  12425. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12426. if (instanceExtension != null) {
  12427. this._caps.instancedArrays = true;
  12428. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12429. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12430. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12431. }
  12432. else {
  12433. this._caps.instancedArrays = false;
  12434. }
  12435. }
  12436. // Intelligently add supported compressed formats in order to check for.
  12437. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12438. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12439. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12440. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12441. if (this._caps.astc)
  12442. this.texturesSupported.push('-astc.ktx');
  12443. if (this._caps.s3tc)
  12444. this.texturesSupported.push('-dxt.ktx');
  12445. if (this._caps.pvrtc)
  12446. this.texturesSupported.push('-pvrtc.ktx');
  12447. if (this._caps.etc2)
  12448. this.texturesSupported.push('-etc2.ktx');
  12449. if (this._caps.etc1)
  12450. this.texturesSupported.push('-etc1.ktx');
  12451. if (this._gl.getShaderPrecisionFormat) {
  12452. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12453. if (highp) {
  12454. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12455. }
  12456. }
  12457. // Depth buffer
  12458. this.setDepthBuffer(true);
  12459. this.setDepthFunctionToLessOrEqual();
  12460. this.setDepthWrite(true);
  12461. // Texture maps
  12462. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12463. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12464. this._nextFreeTextureSlots.push(slot);
  12465. }
  12466. };
  12467. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12468. /**
  12469. * Gets version of the current webGL context
  12470. */
  12471. get: function () {
  12472. return this._webGLVersion;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12478. /**
  12479. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12480. */
  12481. get: function () {
  12482. return this._isStencilEnable;
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. Engine.prototype._prepareWorkingCanvas = function () {
  12488. if (this._workingCanvas) {
  12489. return;
  12490. }
  12491. this._workingCanvas = document.createElement("canvas");
  12492. var context = this._workingCanvas.getContext("2d");
  12493. if (context) {
  12494. this._workingContext = context;
  12495. }
  12496. };
  12497. /**
  12498. * Reset the texture cache to empty state
  12499. */
  12500. Engine.prototype.resetTextureCache = function () {
  12501. for (var key in this._boundTexturesCache) {
  12502. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12503. continue;
  12504. }
  12505. var boundTexture = this._boundTexturesCache[key];
  12506. if (boundTexture) {
  12507. this._removeDesignatedSlot(boundTexture);
  12508. }
  12509. this._boundTexturesCache[key] = null;
  12510. }
  12511. if (!this.disableTextureBindingOptimization) {
  12512. this._nextFreeTextureSlots = [];
  12513. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12514. this._nextFreeTextureSlots.push(slot);
  12515. }
  12516. }
  12517. this._currentTextureChannel = -1;
  12518. };
  12519. /**
  12520. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12521. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12522. * @returns true if engine is in deterministic lock step mode
  12523. */
  12524. Engine.prototype.isDeterministicLockStep = function () {
  12525. return this._deterministicLockstep;
  12526. };
  12527. /**
  12528. * Gets the max steps when engine is running in deterministic lock step
  12529. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12530. * @returns the max steps
  12531. */
  12532. Engine.prototype.getLockstepMaxSteps = function () {
  12533. return this._lockstepMaxSteps;
  12534. };
  12535. /**
  12536. * Gets an object containing information about the current webGL context
  12537. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12538. */
  12539. Engine.prototype.getGlInfo = function () {
  12540. return {
  12541. vendor: this._glVendor,
  12542. renderer: this._glRenderer,
  12543. version: this._glVersion
  12544. };
  12545. };
  12546. /**
  12547. * Gets current aspect ratio
  12548. * @param camera defines the camera to use to get the aspect ratio
  12549. * @param useScreen defines if screen size must be used (or the current render target if any)
  12550. * @returns a number defining the aspect ratio
  12551. */
  12552. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12553. if (useScreen === void 0) { useScreen = false; }
  12554. var viewport = camera.viewport;
  12555. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12556. };
  12557. /**
  12558. * Gets current screen aspect ratio
  12559. * @returns a number defining the aspect ratio
  12560. */
  12561. Engine.prototype.getScreenAspectRatio = function () {
  12562. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12563. };
  12564. /**
  12565. * Gets the current render width
  12566. * @param useScreen defines if screen size must be used (or the current render target if any)
  12567. * @returns a number defining the current render width
  12568. */
  12569. Engine.prototype.getRenderWidth = function (useScreen) {
  12570. if (useScreen === void 0) { useScreen = false; }
  12571. if (!useScreen && this._currentRenderTarget) {
  12572. return this._currentRenderTarget.width;
  12573. }
  12574. return this._gl.drawingBufferWidth;
  12575. };
  12576. /**
  12577. * Gets the current render height
  12578. * @param useScreen defines if screen size must be used (or the current render target if any)
  12579. * @returns a number defining the current render height
  12580. */
  12581. Engine.prototype.getRenderHeight = function (useScreen) {
  12582. if (useScreen === void 0) { useScreen = false; }
  12583. if (!useScreen && this._currentRenderTarget) {
  12584. return this._currentRenderTarget.height;
  12585. }
  12586. return this._gl.drawingBufferHeight;
  12587. };
  12588. /**
  12589. * Gets the HTML canvas attached with the current webGL context
  12590. * @returns a HTML canvas
  12591. */
  12592. Engine.prototype.getRenderingCanvas = function () {
  12593. return this._renderingCanvas;
  12594. };
  12595. /**
  12596. * Gets the client rect of the HTML canvas attached with the current webGL context
  12597. * @returns a client rectanglee
  12598. */
  12599. Engine.prototype.getRenderingCanvasClientRect = function () {
  12600. if (!this._renderingCanvas) {
  12601. return null;
  12602. }
  12603. return this._renderingCanvas.getBoundingClientRect();
  12604. };
  12605. /**
  12606. * Defines the hardware scaling level.
  12607. * By default the hardware scaling level is computed from the window device ratio.
  12608. * 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.
  12609. * @param level defines the level to use
  12610. */
  12611. Engine.prototype.setHardwareScalingLevel = function (level) {
  12612. this._hardwareScalingLevel = level;
  12613. this.resize();
  12614. };
  12615. /**
  12616. * Gets the current hardware scaling level.
  12617. * By default the hardware scaling level is computed from the window device ratio.
  12618. * 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.
  12619. * @returns a number indicating the current hardware scaling level
  12620. */
  12621. Engine.prototype.getHardwareScalingLevel = function () {
  12622. return this._hardwareScalingLevel;
  12623. };
  12624. /**
  12625. * Gets the list of loaded textures
  12626. * @returns an array containing all loaded textures
  12627. */
  12628. Engine.prototype.getLoadedTexturesCache = function () {
  12629. return this._internalTexturesCache;
  12630. };
  12631. /**
  12632. * Gets the object containing all engine capabilities
  12633. * @returns the EngineCapabilities object
  12634. */
  12635. Engine.prototype.getCaps = function () {
  12636. return this._caps;
  12637. };
  12638. Object.defineProperty(Engine.prototype, "drawCalls", {
  12639. /** @hidden */
  12640. get: function () {
  12641. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12642. return 0;
  12643. },
  12644. enumerable: true,
  12645. configurable: true
  12646. });
  12647. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12648. /** @hidden */
  12649. get: function () {
  12650. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12651. return null;
  12652. },
  12653. enumerable: true,
  12654. configurable: true
  12655. });
  12656. /**
  12657. * Gets the current depth function
  12658. * @returns a number defining the depth function
  12659. */
  12660. Engine.prototype.getDepthFunction = function () {
  12661. return this._depthCullingState.depthFunc;
  12662. };
  12663. /**
  12664. * Sets the current depth function
  12665. * @param depthFunc defines the function to use
  12666. */
  12667. Engine.prototype.setDepthFunction = function (depthFunc) {
  12668. this._depthCullingState.depthFunc = depthFunc;
  12669. };
  12670. /**
  12671. * Sets the current depth function to GREATER
  12672. */
  12673. Engine.prototype.setDepthFunctionToGreater = function () {
  12674. this._depthCullingState.depthFunc = this._gl.GREATER;
  12675. };
  12676. /**
  12677. * Sets the current depth function to GEQUAL
  12678. */
  12679. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12680. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12681. };
  12682. /**
  12683. * Sets the current depth function to LESS
  12684. */
  12685. Engine.prototype.setDepthFunctionToLess = function () {
  12686. this._depthCullingState.depthFunc = this._gl.LESS;
  12687. };
  12688. /**
  12689. * Sets the current depth function to LEQUAL
  12690. */
  12691. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12692. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12693. };
  12694. /**
  12695. * Gets a boolean indicating if stencil buffer is enabled
  12696. * @returns the current stencil buffer state
  12697. */
  12698. Engine.prototype.getStencilBuffer = function () {
  12699. return this._stencilState.stencilTest;
  12700. };
  12701. /**
  12702. * Enable or disable the stencil buffer
  12703. * @param enable defines if the stencil buffer must be enabled or disabled
  12704. */
  12705. Engine.prototype.setStencilBuffer = function (enable) {
  12706. this._stencilState.stencilTest = enable;
  12707. };
  12708. /**
  12709. * Gets the current stencil mask
  12710. * @returns a number defining the new stencil mask to use
  12711. */
  12712. Engine.prototype.getStencilMask = function () {
  12713. return this._stencilState.stencilMask;
  12714. };
  12715. /**
  12716. * Sets the current stencil mask
  12717. * @param mask defines the new stencil mask to use
  12718. */
  12719. Engine.prototype.setStencilMask = function (mask) {
  12720. this._stencilState.stencilMask = mask;
  12721. };
  12722. /**
  12723. * Gets the current stencil function
  12724. * @returns a number defining the stencil function to use
  12725. */
  12726. Engine.prototype.getStencilFunction = function () {
  12727. return this._stencilState.stencilFunc;
  12728. };
  12729. /**
  12730. * Gets the current stencil reference value
  12731. * @returns a number defining the stencil reference value to use
  12732. */
  12733. Engine.prototype.getStencilFunctionReference = function () {
  12734. return this._stencilState.stencilFuncRef;
  12735. };
  12736. /**
  12737. * Gets the current stencil mask
  12738. * @returns a number defining the stencil mask to use
  12739. */
  12740. Engine.prototype.getStencilFunctionMask = function () {
  12741. return this._stencilState.stencilFuncMask;
  12742. };
  12743. /**
  12744. * Sets the current stencil function
  12745. * @param stencilFunc defines the new stencil function to use
  12746. */
  12747. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12748. this._stencilState.stencilFunc = stencilFunc;
  12749. };
  12750. /**
  12751. * Sets the current stencil reference
  12752. * @param reference defines the new stencil reference to use
  12753. */
  12754. Engine.prototype.setStencilFunctionReference = function (reference) {
  12755. this._stencilState.stencilFuncRef = reference;
  12756. };
  12757. /**
  12758. * Sets the current stencil mask
  12759. * @param mask defines the new stencil mask to use
  12760. */
  12761. Engine.prototype.setStencilFunctionMask = function (mask) {
  12762. this._stencilState.stencilFuncMask = mask;
  12763. };
  12764. /**
  12765. * Gets the current stencil operation when stencil fails
  12766. * @returns a number defining stencil operation to use when stencil fails
  12767. */
  12768. Engine.prototype.getStencilOperationFail = function () {
  12769. return this._stencilState.stencilOpStencilFail;
  12770. };
  12771. /**
  12772. * Gets the current stencil operation when depth fails
  12773. * @returns a number defining stencil operation to use when depth fails
  12774. */
  12775. Engine.prototype.getStencilOperationDepthFail = function () {
  12776. return this._stencilState.stencilOpDepthFail;
  12777. };
  12778. /**
  12779. * Gets the current stencil operation when stencil passes
  12780. * @returns a number defining stencil operation to use when stencil passes
  12781. */
  12782. Engine.prototype.getStencilOperationPass = function () {
  12783. return this._stencilState.stencilOpStencilDepthPass;
  12784. };
  12785. /**
  12786. * Sets the stencil operation to use when stencil fails
  12787. * @param operation defines the stencil operation to use when stencil fails
  12788. */
  12789. Engine.prototype.setStencilOperationFail = function (operation) {
  12790. this._stencilState.stencilOpStencilFail = operation;
  12791. };
  12792. /**
  12793. * Sets the stencil operation to use when depth fails
  12794. * @param operation defines the stencil operation to use when depth fails
  12795. */
  12796. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12797. this._stencilState.stencilOpDepthFail = operation;
  12798. };
  12799. /**
  12800. * Sets the stencil operation to use when stencil passes
  12801. * @param operation defines the stencil operation to use when stencil passes
  12802. */
  12803. Engine.prototype.setStencilOperationPass = function (operation) {
  12804. this._stencilState.stencilOpStencilDepthPass = operation;
  12805. };
  12806. /**
  12807. * Sets a boolean indicating if the dithering state is enabled or disabled
  12808. * @param value defines the dithering state
  12809. */
  12810. Engine.prototype.setDitheringState = function (value) {
  12811. if (value) {
  12812. this._gl.enable(this._gl.DITHER);
  12813. }
  12814. else {
  12815. this._gl.disable(this._gl.DITHER);
  12816. }
  12817. };
  12818. /**
  12819. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12820. * @param value defines the rasterizer state
  12821. */
  12822. Engine.prototype.setRasterizerState = function (value) {
  12823. if (value) {
  12824. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12825. }
  12826. else {
  12827. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12828. }
  12829. };
  12830. /**
  12831. * stop executing a render loop function and remove it from the execution array
  12832. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12833. */
  12834. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12835. if (!renderFunction) {
  12836. this._activeRenderLoops = [];
  12837. return;
  12838. }
  12839. var index = this._activeRenderLoops.indexOf(renderFunction);
  12840. if (index >= 0) {
  12841. this._activeRenderLoops.splice(index, 1);
  12842. }
  12843. };
  12844. /** @hidden */
  12845. Engine.prototype._renderLoop = function () {
  12846. if (!this._contextWasLost) {
  12847. var shouldRender = true;
  12848. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12849. shouldRender = false;
  12850. }
  12851. if (shouldRender) {
  12852. // Start new frame
  12853. this.beginFrame();
  12854. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12855. var renderFunction = this._activeRenderLoops[index];
  12856. renderFunction();
  12857. }
  12858. // Present
  12859. this.endFrame();
  12860. }
  12861. }
  12862. if (this._activeRenderLoops.length > 0) {
  12863. // Register new frame
  12864. var requester = null;
  12865. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12866. requester = this._vrDisplay;
  12867. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12868. }
  12869. else {
  12870. this._renderingQueueLaunched = false;
  12871. }
  12872. };
  12873. /**
  12874. * Register and execute a render loop. The engine can have more than one render function
  12875. * @param renderFunction defines the function to continuously execute
  12876. */
  12877. Engine.prototype.runRenderLoop = function (renderFunction) {
  12878. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12879. return;
  12880. }
  12881. this._activeRenderLoops.push(renderFunction);
  12882. if (!this._renderingQueueLaunched) {
  12883. this._renderingQueueLaunched = true;
  12884. this._bindedRenderFunction = this._renderLoop.bind(this);
  12885. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12886. }
  12887. };
  12888. /**
  12889. * Toggle full screen mode
  12890. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12891. * @param options defines an option object to be sent to the requestFullscreen function
  12892. */
  12893. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12894. if (this.isFullscreen) {
  12895. BABYLON.Tools.ExitFullscreen();
  12896. }
  12897. else {
  12898. this._pointerLockRequested = requestPointerLock;
  12899. if (this._renderingCanvas) {
  12900. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12901. }
  12902. }
  12903. };
  12904. /**
  12905. * Clear the current render buffer or the current render target (if any is set up)
  12906. * @param color defines the color to use
  12907. * @param backBuffer defines if the back buffer must be cleared
  12908. * @param depth defines if the depth buffer must be cleared
  12909. * @param stencil defines if the stencil buffer must be cleared
  12910. */
  12911. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12912. if (stencil === void 0) { stencil = false; }
  12913. this.applyStates();
  12914. var mode = 0;
  12915. if (backBuffer && color) {
  12916. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12917. mode |= this._gl.COLOR_BUFFER_BIT;
  12918. }
  12919. if (depth) {
  12920. this._gl.clearDepth(1.0);
  12921. mode |= this._gl.DEPTH_BUFFER_BIT;
  12922. }
  12923. if (stencil) {
  12924. this._gl.clearStencil(0);
  12925. mode |= this._gl.STENCIL_BUFFER_BIT;
  12926. }
  12927. this._gl.clear(mode);
  12928. };
  12929. /**
  12930. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12931. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12932. * @param y defines the y-coordinate of the corner of the clear rectangle
  12933. * @param width defines the width of the clear rectangle
  12934. * @param height defines the height of the clear rectangle
  12935. * @param clearColor defines the clear color
  12936. */
  12937. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12938. var gl = this._gl;
  12939. // Save state
  12940. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12941. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12942. // Change state
  12943. gl.enable(gl.SCISSOR_TEST);
  12944. gl.scissor(x, y, width, height);
  12945. // Clear
  12946. this.clear(clearColor, true, true, true);
  12947. // Restore state
  12948. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12949. if (curScissor === true) {
  12950. gl.enable(gl.SCISSOR_TEST);
  12951. }
  12952. else {
  12953. gl.disable(gl.SCISSOR_TEST);
  12954. }
  12955. };
  12956. /** @hidden */
  12957. Engine.prototype._viewport = function (x, y, width, height) {
  12958. if (x !== this._viewportCached.x ||
  12959. y !== this._viewportCached.y ||
  12960. width !== this._viewportCached.z ||
  12961. height !== this._viewportCached.w) {
  12962. this._viewportCached.x = x;
  12963. this._viewportCached.y = y;
  12964. this._viewportCached.z = width;
  12965. this._viewportCached.w = height;
  12966. this._gl.viewport(x, y, width, height);
  12967. }
  12968. };
  12969. /**
  12970. * Set the WebGL's viewport
  12971. * @param viewport defines the viewport element to be used
  12972. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12973. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12974. */
  12975. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12976. var width = requiredWidth || this.getRenderWidth();
  12977. var height = requiredHeight || this.getRenderHeight();
  12978. var x = viewport.x || 0;
  12979. var y = viewport.y || 0;
  12980. this._cachedViewport = viewport;
  12981. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12982. };
  12983. /**
  12984. * Directly set the WebGL Viewport
  12985. * @param x defines the x coordinate of the viewport (in screen space)
  12986. * @param y defines the y coordinate of the viewport (in screen space)
  12987. * @param width defines the width of the viewport (in screen space)
  12988. * @param height defines the height of the viewport (in screen space)
  12989. * @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
  12990. */
  12991. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12992. var currentViewport = this._cachedViewport;
  12993. this._cachedViewport = null;
  12994. this._viewport(x, y, width, height);
  12995. return currentViewport;
  12996. };
  12997. /**
  12998. * Begin a new frame
  12999. */
  13000. Engine.prototype.beginFrame = function () {
  13001. this.onBeginFrameObservable.notifyObservers(this);
  13002. this._measureFps();
  13003. };
  13004. /**
  13005. * Enf the current frame
  13006. */
  13007. Engine.prototype.endFrame = function () {
  13008. // Force a flush in case we are using a bad OS.
  13009. if (this._badOS) {
  13010. this.flushFramebuffer();
  13011. }
  13012. // Submit frame to the vr device, if enabled
  13013. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13014. // TODO: We should only submit the frame if we read frameData successfully.
  13015. this._vrDisplay.submitFrame();
  13016. }
  13017. this.onEndFrameObservable.notifyObservers(this);
  13018. };
  13019. /**
  13020. * Resize the view according to the canvas' size
  13021. */
  13022. Engine.prototype.resize = function () {
  13023. // We're not resizing the size of the canvas while in VR mode & presenting
  13024. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13025. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13026. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13027. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13028. }
  13029. };
  13030. /**
  13031. * Force a specific size of the canvas
  13032. * @param width defines the new canvas' width
  13033. * @param height defines the new canvas' height
  13034. */
  13035. Engine.prototype.setSize = function (width, height) {
  13036. if (!this._renderingCanvas) {
  13037. return;
  13038. }
  13039. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13040. return;
  13041. }
  13042. this._renderingCanvas.width = width;
  13043. this._renderingCanvas.height = height;
  13044. for (var index = 0; index < this.scenes.length; index++) {
  13045. var scene = this.scenes[index];
  13046. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13047. var cam = scene.cameras[camIndex];
  13048. cam._currentRenderId = 0;
  13049. }
  13050. }
  13051. if (this.onResizeObservable.hasObservers) {
  13052. this.onResizeObservable.notifyObservers(this);
  13053. }
  13054. };
  13055. // WebVR functions
  13056. /**
  13057. * Gets a boolean indicating if a webVR device was detected
  13058. * @returns true if a webVR device was detected
  13059. */
  13060. Engine.prototype.isVRDevicePresent = function () {
  13061. return !!this._vrDisplay;
  13062. };
  13063. /**
  13064. * Gets the current webVR device
  13065. * @returns the current webVR device (or null)
  13066. */
  13067. Engine.prototype.getVRDevice = function () {
  13068. return this._vrDisplay;
  13069. };
  13070. /**
  13071. * Initializes a webVR display and starts listening to display change events
  13072. * The onVRDisplayChangedObservable will be notified upon these changes
  13073. * @returns The onVRDisplayChangedObservable
  13074. */
  13075. Engine.prototype.initWebVR = function () {
  13076. this.initWebVRAsync();
  13077. return this.onVRDisplayChangedObservable;
  13078. };
  13079. /**
  13080. * Initializes a webVR display and starts listening to display change events
  13081. * The onVRDisplayChangedObservable will be notified upon these changes
  13082. * @returns A promise containing a VRDisplay and if vr is supported
  13083. */
  13084. Engine.prototype.initWebVRAsync = function () {
  13085. var _this = this;
  13086. var notifyObservers = function () {
  13087. var eventArgs = {
  13088. vrDisplay: _this._vrDisplay,
  13089. vrSupported: _this._vrSupported
  13090. };
  13091. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13092. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13093. };
  13094. if (!this._onVrDisplayConnect) {
  13095. this._onVrDisplayConnect = function (event) {
  13096. _this._vrDisplay = event.display;
  13097. notifyObservers();
  13098. };
  13099. this._onVrDisplayDisconnect = function () {
  13100. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13101. _this._vrDisplay = undefined;
  13102. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13103. notifyObservers();
  13104. };
  13105. this._onVrDisplayPresentChange = function () {
  13106. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13107. };
  13108. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13109. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13110. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13111. }
  13112. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13113. this._webVRInitPromise.then(notifyObservers);
  13114. return this._webVRInitPromise;
  13115. };
  13116. /**
  13117. * Call this function to switch to webVR mode
  13118. * Will do nothing if webVR is not supported or if there is no webVR device
  13119. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13120. */
  13121. Engine.prototype.enableVR = function () {
  13122. var _this = this;
  13123. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13124. var onResolved = function () {
  13125. _this.onVRRequestPresentComplete.notifyObservers(true);
  13126. _this._onVRFullScreenTriggered();
  13127. };
  13128. var onRejected = function () {
  13129. _this.onVRRequestPresentComplete.notifyObservers(false);
  13130. };
  13131. this.onVRRequestPresentStart.notifyObservers(this);
  13132. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13133. }
  13134. };
  13135. /**
  13136. * Call this function to leave webVR mode
  13137. * Will do nothing if webVR is not supported or if there is no webVR device
  13138. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13139. */
  13140. Engine.prototype.disableVR = function () {
  13141. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13142. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13143. }
  13144. };
  13145. Engine.prototype._getVRDisplaysAsync = function () {
  13146. var _this = this;
  13147. return new Promise(function (res, rej) {
  13148. if (navigator.getVRDisplays) {
  13149. navigator.getVRDisplays().then(function (devices) {
  13150. _this._vrSupported = true;
  13151. // note that devices may actually be an empty array. This is fine;
  13152. // we expect this._vrDisplay to be undefined in this case.
  13153. _this._vrDisplay = devices[0];
  13154. res({
  13155. vrDisplay: _this._vrDisplay,
  13156. vrSupported: _this._vrSupported
  13157. });
  13158. });
  13159. }
  13160. else {
  13161. _this._vrDisplay = undefined;
  13162. _this._vrSupported = false;
  13163. res({
  13164. vrDisplay: _this._vrDisplay,
  13165. vrSupported: _this._vrSupported
  13166. });
  13167. }
  13168. });
  13169. };
  13170. /**
  13171. * Binds the frame buffer to the specified texture.
  13172. * @param texture The texture to render to or null for the default canvas
  13173. * @param faceIndex The face of the texture to render to in case of cube texture
  13174. * @param requiredWidth The width of the target to render to
  13175. * @param requiredHeight The height of the target to render to
  13176. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13177. * @param depthStencilTexture The depth stencil texture to use to render
  13178. * @param lodLevel defines le lod level to bind to the frame buffer
  13179. */
  13180. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13181. if (lodLevel === void 0) { lodLevel = 0; }
  13182. if (this._currentRenderTarget) {
  13183. this.unBindFramebuffer(this._currentRenderTarget);
  13184. }
  13185. this._currentRenderTarget = texture;
  13186. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13187. var gl = this._gl;
  13188. if (texture.isCube) {
  13189. if (faceIndex === undefined) {
  13190. faceIndex = 0;
  13191. }
  13192. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13193. if (depthStencilTexture) {
  13194. if (depthStencilTexture._generateStencilBuffer) {
  13195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13196. }
  13197. else {
  13198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13199. }
  13200. }
  13201. }
  13202. if (this._cachedViewport && !forceFullscreenViewport) {
  13203. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13204. }
  13205. else {
  13206. if (!requiredWidth) {
  13207. requiredWidth = texture.width;
  13208. if (lodLevel) {
  13209. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13210. }
  13211. }
  13212. if (!requiredHeight) {
  13213. requiredHeight = texture.height;
  13214. if (lodLevel) {
  13215. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13216. }
  13217. }
  13218. this._viewport(0, 0, requiredWidth, requiredHeight);
  13219. }
  13220. this.wipeCaches();
  13221. };
  13222. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13223. if (this._currentFramebuffer !== framebuffer) {
  13224. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13225. this._currentFramebuffer = framebuffer;
  13226. }
  13227. };
  13228. /**
  13229. * Unbind the current render target texture from the webGL context
  13230. * @param texture defines the render target texture to unbind
  13231. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13232. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13233. */
  13234. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13235. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13236. this._currentRenderTarget = null;
  13237. // If MSAA, we need to bitblt back to main texture
  13238. var gl = this._gl;
  13239. if (texture._MSAAFramebuffer) {
  13240. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13241. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13242. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13243. }
  13244. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13245. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13246. gl.generateMipmap(gl.TEXTURE_2D);
  13247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13248. }
  13249. if (onBeforeUnbind) {
  13250. if (texture._MSAAFramebuffer) {
  13251. // Bind the correct framebuffer
  13252. this.bindUnboundFramebuffer(texture._framebuffer);
  13253. }
  13254. onBeforeUnbind();
  13255. }
  13256. this.bindUnboundFramebuffer(null);
  13257. };
  13258. /**
  13259. * Unbind a list of render target textures from the webGL context
  13260. * This is used only when drawBuffer extension or webGL2 are active
  13261. * @param textures defines the render target textures to unbind
  13262. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13263. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13264. */
  13265. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13266. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13267. this._currentRenderTarget = null;
  13268. // If MSAA, we need to bitblt back to main texture
  13269. var gl = this._gl;
  13270. if (textures[0]._MSAAFramebuffer) {
  13271. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13272. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13273. var attachments = textures[0]._attachments;
  13274. if (!attachments) {
  13275. attachments = new Array(textures.length);
  13276. textures[0]._attachments = attachments;
  13277. }
  13278. for (var i = 0; i < textures.length; i++) {
  13279. var texture = textures[i];
  13280. for (var j = 0; j < attachments.length; j++) {
  13281. attachments[j] = gl.NONE;
  13282. }
  13283. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13284. gl.readBuffer(attachments[i]);
  13285. gl.drawBuffers(attachments);
  13286. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13287. }
  13288. for (var i = 0; i < attachments.length; i++) {
  13289. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13290. }
  13291. gl.drawBuffers(attachments);
  13292. }
  13293. for (var i = 0; i < textures.length; i++) {
  13294. var texture = textures[i];
  13295. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13296. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13297. gl.generateMipmap(gl.TEXTURE_2D);
  13298. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13299. }
  13300. }
  13301. if (onBeforeUnbind) {
  13302. if (textures[0]._MSAAFramebuffer) {
  13303. // Bind the correct framebuffer
  13304. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13305. }
  13306. onBeforeUnbind();
  13307. }
  13308. this.bindUnboundFramebuffer(null);
  13309. };
  13310. /**
  13311. * Force the mipmap generation for the given render target texture
  13312. * @param texture defines the render target texture to use
  13313. */
  13314. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13315. if (texture.generateMipMaps) {
  13316. var gl = this._gl;
  13317. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13318. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13319. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13320. }
  13321. };
  13322. /**
  13323. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13324. */
  13325. Engine.prototype.flushFramebuffer = function () {
  13326. this._gl.flush();
  13327. };
  13328. /**
  13329. * Unbind the current render target and bind the default framebuffer
  13330. */
  13331. Engine.prototype.restoreDefaultFramebuffer = function () {
  13332. if (this._currentRenderTarget) {
  13333. this.unBindFramebuffer(this._currentRenderTarget);
  13334. }
  13335. else {
  13336. this.bindUnboundFramebuffer(null);
  13337. }
  13338. if (this._cachedViewport) {
  13339. this.setViewport(this._cachedViewport);
  13340. }
  13341. this.wipeCaches();
  13342. };
  13343. // UBOs
  13344. /**
  13345. * Create an uniform buffer
  13346. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13347. * @param elements defines the content of the uniform buffer
  13348. * @returns the webGL uniform buffer
  13349. */
  13350. Engine.prototype.createUniformBuffer = function (elements) {
  13351. var ubo = this._gl.createBuffer();
  13352. if (!ubo) {
  13353. throw new Error("Unable to create uniform buffer");
  13354. }
  13355. this.bindUniformBuffer(ubo);
  13356. if (elements instanceof Float32Array) {
  13357. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13358. }
  13359. else {
  13360. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13361. }
  13362. this.bindUniformBuffer(null);
  13363. ubo.references = 1;
  13364. return ubo;
  13365. };
  13366. /**
  13367. * Create a dynamic uniform buffer
  13368. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13369. * @param elements defines the content of the uniform buffer
  13370. * @returns the webGL uniform buffer
  13371. */
  13372. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13373. var ubo = this._gl.createBuffer();
  13374. if (!ubo) {
  13375. throw new Error("Unable to create dynamic uniform buffer");
  13376. }
  13377. this.bindUniformBuffer(ubo);
  13378. if (elements instanceof Float32Array) {
  13379. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13380. }
  13381. else {
  13382. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13383. }
  13384. this.bindUniformBuffer(null);
  13385. ubo.references = 1;
  13386. return ubo;
  13387. };
  13388. /**
  13389. * Update an existing uniform buffer
  13390. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13391. * @param uniformBuffer defines the target uniform buffer
  13392. * @param elements defines the content to update
  13393. * @param offset defines the offset in the uniform buffer where update should start
  13394. * @param count defines the size of the data to update
  13395. */
  13396. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13397. this.bindUniformBuffer(uniformBuffer);
  13398. if (offset === undefined) {
  13399. offset = 0;
  13400. }
  13401. if (count === undefined) {
  13402. if (elements instanceof Float32Array) {
  13403. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13404. }
  13405. else {
  13406. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13407. }
  13408. }
  13409. else {
  13410. if (elements instanceof Float32Array) {
  13411. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13412. }
  13413. else {
  13414. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13415. }
  13416. }
  13417. this.bindUniformBuffer(null);
  13418. };
  13419. // VBOs
  13420. Engine.prototype._resetVertexBufferBinding = function () {
  13421. this.bindArrayBuffer(null);
  13422. this._cachedVertexBuffers = null;
  13423. };
  13424. /**
  13425. * Creates a vertex buffer
  13426. * @param data the data for the vertex buffer
  13427. * @returns the new WebGL static buffer
  13428. */
  13429. Engine.prototype.createVertexBuffer = function (data) {
  13430. var vbo = this._gl.createBuffer();
  13431. if (!vbo) {
  13432. throw new Error("Unable to create vertex buffer");
  13433. }
  13434. this.bindArrayBuffer(vbo);
  13435. if (data instanceof Array) {
  13436. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13437. }
  13438. else {
  13439. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13440. }
  13441. this._resetVertexBufferBinding();
  13442. vbo.references = 1;
  13443. return vbo;
  13444. };
  13445. /**
  13446. * Creates a dynamic vertex buffer
  13447. * @param data the data for the dynamic vertex buffer
  13448. * @returns the new WebGL dynamic buffer
  13449. */
  13450. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13451. var vbo = this._gl.createBuffer();
  13452. if (!vbo) {
  13453. throw new Error("Unable to create dynamic vertex buffer");
  13454. }
  13455. this.bindArrayBuffer(vbo);
  13456. if (data instanceof Array) {
  13457. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13458. }
  13459. else {
  13460. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13461. }
  13462. this._resetVertexBufferBinding();
  13463. vbo.references = 1;
  13464. return vbo;
  13465. };
  13466. /**
  13467. * Update a dynamic index buffer
  13468. * @param indexBuffer defines the target index buffer
  13469. * @param indices defines the data to update
  13470. * @param offset defines the offset in the target index buffer where update should start
  13471. */
  13472. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13473. if (offset === void 0) { offset = 0; }
  13474. // Force cache update
  13475. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13476. this.bindIndexBuffer(indexBuffer);
  13477. var arrayBuffer;
  13478. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13479. arrayBuffer = indices;
  13480. }
  13481. else {
  13482. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13483. }
  13484. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13485. this._resetIndexBufferBinding();
  13486. };
  13487. /**
  13488. * Updates a dynamic vertex buffer.
  13489. * @param vertexBuffer the vertex buffer to update
  13490. * @param data the data used to update the vertex buffer
  13491. * @param byteOffset the byte offset of the data
  13492. * @param byteLength the byte length of the data
  13493. */
  13494. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13495. this.bindArrayBuffer(vertexBuffer);
  13496. if (byteOffset === undefined) {
  13497. byteOffset = 0;
  13498. }
  13499. if (byteLength === undefined) {
  13500. if (data instanceof Array) {
  13501. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13502. }
  13503. else {
  13504. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13505. }
  13506. }
  13507. else {
  13508. if (data instanceof Array) {
  13509. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13510. }
  13511. else {
  13512. if (data instanceof ArrayBuffer) {
  13513. data = new Uint8Array(data, byteOffset, byteLength);
  13514. }
  13515. else {
  13516. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13517. }
  13518. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13519. }
  13520. }
  13521. this._resetVertexBufferBinding();
  13522. };
  13523. Engine.prototype._resetIndexBufferBinding = function () {
  13524. this.bindIndexBuffer(null);
  13525. this._cachedIndexBuffer = null;
  13526. };
  13527. /**
  13528. * Creates a new index buffer
  13529. * @param indices defines the content of the index buffer
  13530. * @param updatable defines if the index buffer must be updatable
  13531. * @returns a new webGL buffer
  13532. */
  13533. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13534. var vbo = this._gl.createBuffer();
  13535. if (!vbo) {
  13536. throw new Error("Unable to create index buffer");
  13537. }
  13538. this.bindIndexBuffer(vbo);
  13539. // Check for 32 bits indices
  13540. var arrayBuffer;
  13541. var need32Bits = false;
  13542. if (indices instanceof Uint16Array) {
  13543. arrayBuffer = indices;
  13544. }
  13545. else {
  13546. //check 32 bit support
  13547. if (this._caps.uintIndices) {
  13548. if (indices instanceof Uint32Array) {
  13549. arrayBuffer = indices;
  13550. need32Bits = true;
  13551. }
  13552. else {
  13553. //number[] or Int32Array, check if 32 bit is necessary
  13554. for (var index = 0; index < indices.length; index++) {
  13555. if (indices[index] > 65535) {
  13556. need32Bits = true;
  13557. break;
  13558. }
  13559. }
  13560. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13561. }
  13562. }
  13563. else {
  13564. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13565. arrayBuffer = new Uint16Array(indices);
  13566. }
  13567. }
  13568. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13569. this._resetIndexBufferBinding();
  13570. vbo.references = 1;
  13571. vbo.is32Bits = need32Bits;
  13572. return vbo;
  13573. };
  13574. /**
  13575. * Bind a webGL buffer to the webGL context
  13576. * @param buffer defines the buffer to bind
  13577. */
  13578. Engine.prototype.bindArrayBuffer = function (buffer) {
  13579. if (!this._vaoRecordInProgress) {
  13580. this._unbindVertexArrayObject();
  13581. }
  13582. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13583. };
  13584. /**
  13585. * Bind an uniform buffer to the current webGL context
  13586. * @param buffer defines the buffer to bind
  13587. */
  13588. Engine.prototype.bindUniformBuffer = function (buffer) {
  13589. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13590. };
  13591. /**
  13592. * Bind a buffer to the current webGL context at a given location
  13593. * @param buffer defines the buffer to bind
  13594. * @param location defines the index where to bind the buffer
  13595. */
  13596. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13597. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13598. };
  13599. /**
  13600. * Bind a specific block at a given index in a specific shader program
  13601. * @param shaderProgram defines the shader program
  13602. * @param blockName defines the block name
  13603. * @param index defines the index where to bind the block
  13604. */
  13605. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13606. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13607. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13608. };
  13609. ;
  13610. Engine.prototype.bindIndexBuffer = function (buffer) {
  13611. if (!this._vaoRecordInProgress) {
  13612. this._unbindVertexArrayObject();
  13613. }
  13614. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13615. };
  13616. Engine.prototype.bindBuffer = function (buffer, target) {
  13617. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13618. this._gl.bindBuffer(target, buffer);
  13619. this._currentBoundBuffer[target] = buffer;
  13620. }
  13621. };
  13622. /**
  13623. * update the bound buffer with the given data
  13624. * @param data defines the data to update
  13625. */
  13626. Engine.prototype.updateArrayBuffer = function (data) {
  13627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13628. };
  13629. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13630. var pointer = this._currentBufferPointers[indx];
  13631. var changed = false;
  13632. if (!pointer.active) {
  13633. changed = true;
  13634. pointer.active = true;
  13635. pointer.index = indx;
  13636. pointer.size = size;
  13637. pointer.type = type;
  13638. pointer.normalized = normalized;
  13639. pointer.stride = stride;
  13640. pointer.offset = offset;
  13641. pointer.buffer = buffer;
  13642. }
  13643. else {
  13644. if (pointer.buffer !== buffer) {
  13645. pointer.buffer = buffer;
  13646. changed = true;
  13647. }
  13648. if (pointer.size !== size) {
  13649. pointer.size = size;
  13650. changed = true;
  13651. }
  13652. if (pointer.type !== type) {
  13653. pointer.type = type;
  13654. changed = true;
  13655. }
  13656. if (pointer.normalized !== normalized) {
  13657. pointer.normalized = normalized;
  13658. changed = true;
  13659. }
  13660. if (pointer.stride !== stride) {
  13661. pointer.stride = stride;
  13662. changed = true;
  13663. }
  13664. if (pointer.offset !== offset) {
  13665. pointer.offset = offset;
  13666. changed = true;
  13667. }
  13668. }
  13669. if (changed || this._vaoRecordInProgress) {
  13670. this.bindArrayBuffer(buffer);
  13671. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13672. }
  13673. };
  13674. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13675. if (indexBuffer == null) {
  13676. return;
  13677. }
  13678. if (this._cachedIndexBuffer !== indexBuffer) {
  13679. this._cachedIndexBuffer = indexBuffer;
  13680. this.bindIndexBuffer(indexBuffer);
  13681. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13682. }
  13683. };
  13684. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13685. var attributes = effect.getAttributesNames();
  13686. if (!this._vaoRecordInProgress) {
  13687. this._unbindVertexArrayObject();
  13688. }
  13689. this.unbindAllAttributes();
  13690. for (var index = 0; index < attributes.length; index++) {
  13691. var order = effect.getAttributeLocation(index);
  13692. if (order >= 0) {
  13693. var vertexBuffer = vertexBuffers[attributes[index]];
  13694. if (!vertexBuffer) {
  13695. continue;
  13696. }
  13697. this._gl.enableVertexAttribArray(order);
  13698. if (!this._vaoRecordInProgress) {
  13699. this._vertexAttribArraysEnabled[order] = true;
  13700. }
  13701. var buffer = vertexBuffer.getBuffer();
  13702. if (buffer) {
  13703. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13704. if (vertexBuffer.getIsInstanced()) {
  13705. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13706. if (!this._vaoRecordInProgress) {
  13707. this._currentInstanceLocations.push(order);
  13708. this._currentInstanceBuffers.push(buffer);
  13709. }
  13710. }
  13711. }
  13712. }
  13713. }
  13714. };
  13715. /**
  13716. * Records a vertex array object
  13717. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13718. * @param vertexBuffers defines the list of vertex buffers to store
  13719. * @param indexBuffer defines the index buffer to store
  13720. * @param effect defines the effect to store
  13721. * @returns the new vertex array object
  13722. */
  13723. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13724. var vao = this._gl.createVertexArray();
  13725. this._vaoRecordInProgress = true;
  13726. this._gl.bindVertexArray(vao);
  13727. this._mustWipeVertexAttributes = true;
  13728. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13729. this.bindIndexBuffer(indexBuffer);
  13730. this._vaoRecordInProgress = false;
  13731. this._gl.bindVertexArray(null);
  13732. return vao;
  13733. };
  13734. /**
  13735. * Bind a specific vertex array object
  13736. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13737. * @param vertexArrayObject defines the vertex array object to bind
  13738. * @param indexBuffer defines the index buffer to bind
  13739. */
  13740. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13741. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13742. this._cachedVertexArrayObject = vertexArrayObject;
  13743. this._gl.bindVertexArray(vertexArrayObject);
  13744. this._cachedVertexBuffers = null;
  13745. this._cachedIndexBuffer = null;
  13746. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13747. this._mustWipeVertexAttributes = true;
  13748. }
  13749. };
  13750. /**
  13751. * Bind webGl buffers directly to the webGL context
  13752. * @param vertexBuffer defines the vertex buffer to bind
  13753. * @param indexBuffer defines the index buffer to bind
  13754. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13755. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13756. * @param effect defines the effect associated with the vertex buffer
  13757. */
  13758. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13759. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13760. this._cachedVertexBuffers = vertexBuffer;
  13761. this._cachedEffectForVertexBuffers = effect;
  13762. var attributesCount = effect.getAttributesCount();
  13763. this._unbindVertexArrayObject();
  13764. this.unbindAllAttributes();
  13765. var offset = 0;
  13766. for (var index = 0; index < attributesCount; index++) {
  13767. if (index < vertexDeclaration.length) {
  13768. var order = effect.getAttributeLocation(index);
  13769. if (order >= 0) {
  13770. this._gl.enableVertexAttribArray(order);
  13771. this._vertexAttribArraysEnabled[order] = true;
  13772. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13773. }
  13774. offset += vertexDeclaration[index] * 4;
  13775. }
  13776. }
  13777. }
  13778. this._bindIndexBufferWithCache(indexBuffer);
  13779. };
  13780. Engine.prototype._unbindVertexArrayObject = function () {
  13781. if (!this._cachedVertexArrayObject) {
  13782. return;
  13783. }
  13784. this._cachedVertexArrayObject = null;
  13785. this._gl.bindVertexArray(null);
  13786. };
  13787. /**
  13788. * Bind a list of vertex buffers to the webGL context
  13789. * @param vertexBuffers defines the list of vertex buffers to bind
  13790. * @param indexBuffer defines the index buffer to bind
  13791. * @param effect defines the effect associated with the vertex buffers
  13792. */
  13793. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13794. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13795. this._cachedVertexBuffers = vertexBuffers;
  13796. this._cachedEffectForVertexBuffers = effect;
  13797. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13798. }
  13799. this._bindIndexBufferWithCache(indexBuffer);
  13800. };
  13801. /**
  13802. * Unbind all instance attributes
  13803. */
  13804. Engine.prototype.unbindInstanceAttributes = function () {
  13805. var boundBuffer;
  13806. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13807. var instancesBuffer = this._currentInstanceBuffers[i];
  13808. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13809. boundBuffer = instancesBuffer;
  13810. this.bindArrayBuffer(instancesBuffer);
  13811. }
  13812. var offsetLocation = this._currentInstanceLocations[i];
  13813. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13814. }
  13815. this._currentInstanceBuffers.length = 0;
  13816. this._currentInstanceLocations.length = 0;
  13817. };
  13818. /**
  13819. * Release and free the memory of a vertex array object
  13820. * @param vao defines the vertex array object to delete
  13821. */
  13822. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13823. this._gl.deleteVertexArray(vao);
  13824. };
  13825. /** @hidden */
  13826. Engine.prototype._releaseBuffer = function (buffer) {
  13827. buffer.references--;
  13828. if (buffer.references === 0) {
  13829. this._gl.deleteBuffer(buffer);
  13830. return true;
  13831. }
  13832. return false;
  13833. };
  13834. /**
  13835. * Creates a webGL buffer to use with instanciation
  13836. * @param capacity defines the size of the buffer
  13837. * @returns the webGL buffer
  13838. */
  13839. Engine.prototype.createInstancesBuffer = function (capacity) {
  13840. var buffer = this._gl.createBuffer();
  13841. if (!buffer) {
  13842. throw new Error("Unable to create instance buffer");
  13843. }
  13844. buffer.capacity = capacity;
  13845. this.bindArrayBuffer(buffer);
  13846. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13847. return buffer;
  13848. };
  13849. /**
  13850. * Delete a webGL buffer used with instanciation
  13851. * @param buffer defines the webGL buffer to delete
  13852. */
  13853. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13854. this._gl.deleteBuffer(buffer);
  13855. };
  13856. /**
  13857. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13858. * @param instancesBuffer defines the webGL buffer to update and bind
  13859. * @param data defines the data to store in the buffer
  13860. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13861. */
  13862. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13863. this.bindArrayBuffer(instancesBuffer);
  13864. if (data) {
  13865. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13866. }
  13867. if (offsetLocations[0].index !== undefined) {
  13868. var stride = 0;
  13869. for (var i = 0; i < offsetLocations.length; i++) {
  13870. var ai = offsetLocations[i];
  13871. stride += ai.attributeSize * 4;
  13872. }
  13873. for (var i = 0; i < offsetLocations.length; i++) {
  13874. var ai = offsetLocations[i];
  13875. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13876. this._gl.enableVertexAttribArray(ai.index);
  13877. this._vertexAttribArraysEnabled[ai.index] = true;
  13878. }
  13879. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13880. this._gl.vertexAttribDivisor(ai.index, 1);
  13881. this._currentInstanceLocations.push(ai.index);
  13882. this._currentInstanceBuffers.push(instancesBuffer);
  13883. }
  13884. }
  13885. else {
  13886. for (var index = 0; index < 4; index++) {
  13887. var offsetLocation = offsetLocations[index];
  13888. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13889. this._gl.enableVertexAttribArray(offsetLocation);
  13890. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13891. }
  13892. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13893. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13894. this._currentInstanceLocations.push(offsetLocation);
  13895. this._currentInstanceBuffers.push(instancesBuffer);
  13896. }
  13897. }
  13898. };
  13899. /**
  13900. * Apply all cached states (depth, culling, stencil and alpha)
  13901. */
  13902. Engine.prototype.applyStates = function () {
  13903. this._depthCullingState.apply(this._gl);
  13904. this._stencilState.apply(this._gl);
  13905. this._alphaState.apply(this._gl);
  13906. };
  13907. /**
  13908. * Send a draw order
  13909. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13910. * @param indexStart defines the starting index
  13911. * @param indexCount defines the number of index to draw
  13912. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13913. */
  13914. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13915. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13916. };
  13917. /**
  13918. * Draw a list of points
  13919. * @param verticesStart defines the index of first vertex to draw
  13920. * @param verticesCount defines the count of vertices to draw
  13921. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13922. */
  13923. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13924. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13925. };
  13926. /**
  13927. * Draw a list of unindexed primitives
  13928. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13929. * @param verticesStart defines the index of first vertex to draw
  13930. * @param verticesCount defines the count of vertices to draw
  13931. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13932. */
  13933. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13934. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13935. };
  13936. /**
  13937. * Draw a list of indexed primitives
  13938. * @param fillMode defines the primitive to use
  13939. * @param indexStart defines the starting index
  13940. * @param indexCount defines the number of index to draw
  13941. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13942. */
  13943. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13944. // Apply states
  13945. this.applyStates();
  13946. this._drawCalls.addCount(1, false);
  13947. // Render
  13948. var drawMode = this._drawMode(fillMode);
  13949. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13950. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13951. if (instancesCount) {
  13952. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13953. }
  13954. else {
  13955. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13956. }
  13957. };
  13958. /**
  13959. * Draw a list of unindexed primitives
  13960. * @param fillMode defines the primitive to use
  13961. * @param verticesStart defines the index of first vertex to draw
  13962. * @param verticesCount defines the count of vertices to draw
  13963. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13964. */
  13965. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13966. // Apply states
  13967. this.applyStates();
  13968. this._drawCalls.addCount(1, false);
  13969. var drawMode = this._drawMode(fillMode);
  13970. if (instancesCount) {
  13971. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13972. }
  13973. else {
  13974. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13975. }
  13976. };
  13977. Engine.prototype._drawMode = function (fillMode) {
  13978. switch (fillMode) {
  13979. // Triangle views
  13980. case BABYLON.Material.TriangleFillMode:
  13981. return this._gl.TRIANGLES;
  13982. case BABYLON.Material.PointFillMode:
  13983. return this._gl.POINTS;
  13984. case BABYLON.Material.WireFrameFillMode:
  13985. return this._gl.LINES;
  13986. // Draw modes
  13987. case BABYLON.Material.PointListDrawMode:
  13988. return this._gl.POINTS;
  13989. case BABYLON.Material.LineListDrawMode:
  13990. return this._gl.LINES;
  13991. case BABYLON.Material.LineLoopDrawMode:
  13992. return this._gl.LINE_LOOP;
  13993. case BABYLON.Material.LineStripDrawMode:
  13994. return this._gl.LINE_STRIP;
  13995. case BABYLON.Material.TriangleStripDrawMode:
  13996. return this._gl.TRIANGLE_STRIP;
  13997. case BABYLON.Material.TriangleFanDrawMode:
  13998. return this._gl.TRIANGLE_FAN;
  13999. default:
  14000. return this._gl.TRIANGLES;
  14001. }
  14002. };
  14003. // Shaders
  14004. /** @hidden */
  14005. Engine.prototype._releaseEffect = function (effect) {
  14006. if (this._compiledEffects[effect._key]) {
  14007. delete this._compiledEffects[effect._key];
  14008. this._deleteProgram(effect.getProgram());
  14009. }
  14010. };
  14011. /** @hidden */
  14012. Engine.prototype._deleteProgram = function (program) {
  14013. if (program) {
  14014. program.__SPECTOR_rebuildProgram = null;
  14015. if (program.transformFeedback) {
  14016. this.deleteTransformFeedback(program.transformFeedback);
  14017. program.transformFeedback = null;
  14018. }
  14019. this._gl.deleteProgram(program);
  14020. }
  14021. };
  14022. /**
  14023. * Create a new effect (used to store vertex/fragment shaders)
  14024. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14025. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14026. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14027. * @param samplers defines an array of string used to represent textures
  14028. * @param defines defines the string containing the defines to use to compile the shaders
  14029. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14030. * @param onCompiled defines a function to call when the effect creation is successful
  14031. * @param onError defines a function to call when the effect creation has failed
  14032. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14033. * @returns the new Effect
  14034. */
  14035. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14036. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14037. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14038. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14039. if (this._compiledEffects[name]) {
  14040. var compiledEffect = this._compiledEffects[name];
  14041. if (onCompiled && compiledEffect.isReady()) {
  14042. onCompiled(compiledEffect);
  14043. }
  14044. return compiledEffect;
  14045. }
  14046. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14047. effect._key = name;
  14048. this._compiledEffects[name] = effect;
  14049. return effect;
  14050. };
  14051. /**
  14052. * Create an effect to use with particle systems.
  14053. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14054. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14055. * @param uniformsNames defines a list of attribute names
  14056. * @param samplers defines an array of string used to represent textures
  14057. * @param defines defines the string containing the defines to use to compile the shaders
  14058. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14059. * @param onCompiled defines a function to call when the effect creation is successful
  14060. * @param onError defines a function to call when the effect creation has failed
  14061. * @returns the new Effect
  14062. */
  14063. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14064. if (uniformsNames === void 0) { uniformsNames = []; }
  14065. if (samplers === void 0) { samplers = []; }
  14066. if (defines === void 0) { defines = ""; }
  14067. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14068. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14069. if (defines.indexOf(" BILLBOARD") === -1) {
  14070. defines += "\n#define BILLBOARD\n";
  14071. }
  14072. if (samplers.indexOf("diffuseSampler") === -1) {
  14073. samplers.push("diffuseSampler");
  14074. }
  14075. return this.createEffect({
  14076. vertex: "particles",
  14077. fragmentElement: fragmentName
  14078. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14079. };
  14080. /**
  14081. * Directly creates a webGL program
  14082. * @param vertexCode defines the vertex shader code to use
  14083. * @param fragmentCode defines the fragment shader code to use
  14084. * @param context defines the webGL context to use (if not set, the current one will be used)
  14085. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14086. * @returns the new webGL program
  14087. */
  14088. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14089. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14090. context = context || this._gl;
  14091. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14092. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14093. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14094. };
  14095. /**
  14096. * Creates a webGL program
  14097. * @param vertexCode defines the vertex shader code to use
  14098. * @param fragmentCode defines the fragment shader code to use
  14099. * @param defines defines the string containing the defines to use to compile the shaders
  14100. * @param context defines the webGL context to use (if not set, the current one will be used)
  14101. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14102. * @returns the new webGL program
  14103. */
  14104. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14105. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14106. context = context || this._gl;
  14107. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14108. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14109. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14110. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14111. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14112. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14113. return program;
  14114. };
  14115. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14116. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14117. var shaderProgram = context.createProgram();
  14118. if (!shaderProgram) {
  14119. throw new Error("Unable to create program");
  14120. }
  14121. context.attachShader(shaderProgram, vertexShader);
  14122. context.attachShader(shaderProgram, fragmentShader);
  14123. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14124. var transformFeedback = this.createTransformFeedback();
  14125. this.bindTransformFeedback(transformFeedback);
  14126. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14127. shaderProgram.transformFeedback = transformFeedback;
  14128. }
  14129. context.linkProgram(shaderProgram);
  14130. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14131. this.bindTransformFeedback(null);
  14132. }
  14133. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14134. if (!linked) {
  14135. var error = context.getProgramInfoLog(shaderProgram);
  14136. if (error) {
  14137. throw new Error(error);
  14138. }
  14139. }
  14140. if (this.validateShaderPrograms) {
  14141. context.validateProgram(shaderProgram);
  14142. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14143. if (!validated) {
  14144. var error = context.getProgramInfoLog(shaderProgram);
  14145. if (error) {
  14146. throw new Error(error);
  14147. }
  14148. }
  14149. }
  14150. context.deleteShader(vertexShader);
  14151. context.deleteShader(fragmentShader);
  14152. return shaderProgram;
  14153. };
  14154. /**
  14155. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14156. * @param shaderProgram defines the webGL program to use
  14157. * @param uniformsNames defines the list of uniform names
  14158. * @returns an array of webGL uniform locations
  14159. */
  14160. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14161. var results = new Array();
  14162. for (var index = 0; index < uniformsNames.length; index++) {
  14163. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14164. }
  14165. return results;
  14166. };
  14167. /**
  14168. * Gets the lsit of active attributes for a given webGL program
  14169. * @param shaderProgram defines the webGL program to use
  14170. * @param attributesNames defines the list of attribute names to get
  14171. * @returns an array of indices indicating the offset of each attribute
  14172. */
  14173. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14174. var results = [];
  14175. for (var index = 0; index < attributesNames.length; index++) {
  14176. try {
  14177. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14178. }
  14179. catch (e) {
  14180. results.push(-1);
  14181. }
  14182. }
  14183. return results;
  14184. };
  14185. /**
  14186. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14187. * @param effect defines the effect to activate
  14188. */
  14189. Engine.prototype.enableEffect = function (effect) {
  14190. if (!effect) {
  14191. return;
  14192. }
  14193. // Use program
  14194. this.bindSamplers(effect);
  14195. this._currentEffect = effect;
  14196. if (effect.onBind) {
  14197. effect.onBind(effect);
  14198. }
  14199. effect.onBindObservable.notifyObservers(effect);
  14200. };
  14201. /**
  14202. * Set the value of an uniform to an array of int32
  14203. * @param uniform defines the webGL uniform location where to store the value
  14204. * @param array defines the array of int32 to store
  14205. */
  14206. Engine.prototype.setIntArray = function (uniform, array) {
  14207. if (!uniform)
  14208. return;
  14209. this._gl.uniform1iv(uniform, array);
  14210. };
  14211. /**
  14212. * Set the value of an uniform to an array of int32 (stored as vec2)
  14213. * @param uniform defines the webGL uniform location where to store the value
  14214. * @param array defines the array of int32 to store
  14215. */
  14216. Engine.prototype.setIntArray2 = function (uniform, array) {
  14217. if (!uniform || array.length % 2 !== 0)
  14218. return;
  14219. this._gl.uniform2iv(uniform, array);
  14220. };
  14221. /**
  14222. * Set the value of an uniform to an array of int32 (stored as vec3)
  14223. * @param uniform defines the webGL uniform location where to store the value
  14224. * @param array defines the array of int32 to store
  14225. */
  14226. Engine.prototype.setIntArray3 = function (uniform, array) {
  14227. if (!uniform || array.length % 3 !== 0)
  14228. return;
  14229. this._gl.uniform3iv(uniform, array);
  14230. };
  14231. /**
  14232. * Set the value of an uniform to an array of int32 (stored as vec4)
  14233. * @param uniform defines the webGL uniform location where to store the value
  14234. * @param array defines the array of int32 to store
  14235. */
  14236. Engine.prototype.setIntArray4 = function (uniform, array) {
  14237. if (!uniform || array.length % 4 !== 0)
  14238. return;
  14239. this._gl.uniform4iv(uniform, array);
  14240. };
  14241. /**
  14242. * Set the value of an uniform to an array of float32
  14243. * @param uniform defines the webGL uniform location where to store the value
  14244. * @param array defines the array of float32 to store
  14245. */
  14246. Engine.prototype.setFloatArray = function (uniform, array) {
  14247. if (!uniform)
  14248. return;
  14249. this._gl.uniform1fv(uniform, array);
  14250. };
  14251. /**
  14252. * Set the value of an uniform to an array of float32 (stored as vec2)
  14253. * @param uniform defines the webGL uniform location where to store the value
  14254. * @param array defines the array of float32 to store
  14255. */
  14256. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14257. if (!uniform || array.length % 2 !== 0)
  14258. return;
  14259. this._gl.uniform2fv(uniform, array);
  14260. };
  14261. /**
  14262. * Set the value of an uniform to an array of float32 (stored as vec3)
  14263. * @param uniform defines the webGL uniform location where to store the value
  14264. * @param array defines the array of float32 to store
  14265. */
  14266. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14267. if (!uniform || array.length % 3 !== 0)
  14268. return;
  14269. this._gl.uniform3fv(uniform, array);
  14270. };
  14271. /**
  14272. * Set the value of an uniform to an array of float32 (stored as vec4)
  14273. * @param uniform defines the webGL uniform location where to store the value
  14274. * @param array defines the array of float32 to store
  14275. */
  14276. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14277. if (!uniform || array.length % 4 !== 0)
  14278. return;
  14279. this._gl.uniform4fv(uniform, array);
  14280. };
  14281. /**
  14282. * Set the value of an uniform to an array of number
  14283. * @param uniform defines the webGL uniform location where to store the value
  14284. * @param array defines the array of number to store
  14285. */
  14286. Engine.prototype.setArray = function (uniform, array) {
  14287. if (!uniform)
  14288. return;
  14289. this._gl.uniform1fv(uniform, array);
  14290. };
  14291. /**
  14292. * Set the value of an uniform to an array of number (stored as vec2)
  14293. * @param uniform defines the webGL uniform location where to store the value
  14294. * @param array defines the array of number to store
  14295. */
  14296. Engine.prototype.setArray2 = function (uniform, array) {
  14297. if (!uniform || array.length % 2 !== 0)
  14298. return;
  14299. this._gl.uniform2fv(uniform, array);
  14300. };
  14301. /**
  14302. * Set the value of an uniform to an array of number (stored as vec3)
  14303. * @param uniform defines the webGL uniform location where to store the value
  14304. * @param array defines the array of number to store
  14305. */
  14306. Engine.prototype.setArray3 = function (uniform, array) {
  14307. if (!uniform || array.length % 3 !== 0)
  14308. return;
  14309. this._gl.uniform3fv(uniform, array);
  14310. };
  14311. /**
  14312. * Set the value of an uniform to an array of number (stored as vec4)
  14313. * @param uniform defines the webGL uniform location where to store the value
  14314. * @param array defines the array of number to store
  14315. */
  14316. Engine.prototype.setArray4 = function (uniform, array) {
  14317. if (!uniform || array.length % 4 !== 0)
  14318. return;
  14319. this._gl.uniform4fv(uniform, array);
  14320. };
  14321. /**
  14322. * Set the value of an uniform to an array of float32 (stored as matrices)
  14323. * @param uniform defines the webGL uniform location where to store the value
  14324. * @param matrices defines the array of float32 to store
  14325. */
  14326. Engine.prototype.setMatrices = function (uniform, matrices) {
  14327. if (!uniform)
  14328. return;
  14329. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14330. };
  14331. /**
  14332. * Set the value of an uniform to a matrix
  14333. * @param uniform defines the webGL uniform location where to store the value
  14334. * @param matrix defines the matrix to store
  14335. */
  14336. Engine.prototype.setMatrix = function (uniform, matrix) {
  14337. if (!uniform)
  14338. return;
  14339. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14340. };
  14341. /**
  14342. * Set the value of an uniform to a matrix (3x3)
  14343. * @param uniform defines the webGL uniform location where to store the value
  14344. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14345. */
  14346. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14347. if (!uniform)
  14348. return;
  14349. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14350. };
  14351. /**
  14352. * Set the value of an uniform to a matrix (2x2)
  14353. * @param uniform defines the webGL uniform location where to store the value
  14354. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14355. */
  14356. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a number (int)
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param value defines the int number to store
  14365. */
  14366. Engine.prototype.setInt = function (uniform, value) {
  14367. if (!uniform)
  14368. return;
  14369. this._gl.uniform1i(uniform, value);
  14370. };
  14371. /**
  14372. * Set the value of an uniform to a number (float)
  14373. * @param uniform defines the webGL uniform location where to store the value
  14374. * @param value defines the float number to store
  14375. */
  14376. Engine.prototype.setFloat = function (uniform, value) {
  14377. if (!uniform)
  14378. return;
  14379. this._gl.uniform1f(uniform, value);
  14380. };
  14381. /**
  14382. * Set the value of an uniform to a vec2
  14383. * @param uniform defines the webGL uniform location where to store the value
  14384. * @param x defines the 1st component of the value
  14385. * @param y defines the 2nd component of the value
  14386. */
  14387. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14388. if (!uniform)
  14389. return;
  14390. this._gl.uniform2f(uniform, x, y);
  14391. };
  14392. /**
  14393. * Set the value of an uniform to a vec3
  14394. * @param uniform defines the webGL uniform location where to store the value
  14395. * @param x defines the 1st component of the value
  14396. * @param y defines the 2nd component of the value
  14397. * @param z defines the 3rd component of the value
  14398. */
  14399. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14400. if (!uniform)
  14401. return;
  14402. this._gl.uniform3f(uniform, x, y, z);
  14403. };
  14404. /**
  14405. * Set the value of an uniform to a boolean
  14406. * @param uniform defines the webGL uniform location where to store the value
  14407. * @param bool defines the boolean to store
  14408. */
  14409. Engine.prototype.setBool = function (uniform, bool) {
  14410. if (!uniform)
  14411. return;
  14412. this._gl.uniform1i(uniform, bool);
  14413. };
  14414. /**
  14415. * Set the value of an uniform to a vec4
  14416. * @param uniform defines the webGL uniform location where to store the value
  14417. * @param x defines the 1st component of the value
  14418. * @param y defines the 2nd component of the value
  14419. * @param z defines the 3rd component of the value
  14420. * @param w defines the 4th component of the value
  14421. */
  14422. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14423. if (!uniform)
  14424. return;
  14425. this._gl.uniform4f(uniform, x, y, z, w);
  14426. };
  14427. /**
  14428. * Set the value of an uniform to a Color3
  14429. * @param uniform defines the webGL uniform location where to store the value
  14430. * @param color3 defines the color to store
  14431. */
  14432. Engine.prototype.setColor3 = function (uniform, color3) {
  14433. if (!uniform)
  14434. return;
  14435. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14436. };
  14437. /**
  14438. * Set the value of an uniform to a Color3 and an alpha value
  14439. * @param uniform defines the webGL uniform location where to store the value
  14440. * @param color3 defines the color to store
  14441. * @param alpha defines the alpha component to store
  14442. */
  14443. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14444. if (!uniform)
  14445. return;
  14446. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14447. };
  14448. /**
  14449. * Sets a Color4 on a uniform variable
  14450. * @param uniform defines the uniform location
  14451. * @param color4 defines the value to be set
  14452. */
  14453. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14454. if (!uniform)
  14455. return;
  14456. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14457. };
  14458. // States
  14459. /**
  14460. * Set various states to the webGL context
  14461. * @param culling defines backface culling state
  14462. * @param zOffset defines the value to apply to zOffset (0 by default)
  14463. * @param force defines if states must be applied even if cache is up to date
  14464. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14465. */
  14466. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14467. if (zOffset === void 0) { zOffset = 0; }
  14468. if (reverseSide === void 0) { reverseSide = false; }
  14469. // Culling
  14470. if (this._depthCullingState.cull !== culling || force) {
  14471. this._depthCullingState.cull = culling;
  14472. }
  14473. // Cull face
  14474. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14475. if (this._depthCullingState.cullFace !== cullFace || force) {
  14476. this._depthCullingState.cullFace = cullFace;
  14477. }
  14478. // Z offset
  14479. this.setZOffset(zOffset);
  14480. // Front face
  14481. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14482. if (this._depthCullingState.frontFace !== frontFace || force) {
  14483. this._depthCullingState.frontFace = frontFace;
  14484. }
  14485. };
  14486. /**
  14487. * Set the z offset to apply to current rendering
  14488. * @param value defines the offset to apply
  14489. */
  14490. Engine.prototype.setZOffset = function (value) {
  14491. this._depthCullingState.zOffset = value;
  14492. };
  14493. /**
  14494. * Gets the current value of the zOffset
  14495. * @returns the current zOffset state
  14496. */
  14497. Engine.prototype.getZOffset = function () {
  14498. return this._depthCullingState.zOffset;
  14499. };
  14500. /**
  14501. * Enable or disable depth buffering
  14502. * @param enable defines the state to set
  14503. */
  14504. Engine.prototype.setDepthBuffer = function (enable) {
  14505. this._depthCullingState.depthTest = enable;
  14506. };
  14507. /**
  14508. * Gets a boolean indicating if depth writing is enabled
  14509. * @returns the current depth writing state
  14510. */
  14511. Engine.prototype.getDepthWrite = function () {
  14512. return this._depthCullingState.depthMask;
  14513. };
  14514. /**
  14515. * Enable or disable depth writing
  14516. * @param enable defines the state to set
  14517. */
  14518. Engine.prototype.setDepthWrite = function (enable) {
  14519. this._depthCullingState.depthMask = enable;
  14520. };
  14521. /**
  14522. * Enable or disable color writing
  14523. * @param enable defines the state to set
  14524. */
  14525. Engine.prototype.setColorWrite = function (enable) {
  14526. this._gl.colorMask(enable, enable, enable, enable);
  14527. this._colorWrite = enable;
  14528. };
  14529. /**
  14530. * Gets a boolean indicating if color writing is enabled
  14531. * @returns the current color writing state
  14532. */
  14533. Engine.prototype.getColorWrite = function () {
  14534. return this._colorWrite;
  14535. };
  14536. /**
  14537. * Sets alpha constants used by some alpha blending modes
  14538. * @param r defines the red component
  14539. * @param g defines the green component
  14540. * @param b defines the blue component
  14541. * @param a defines the alpha component
  14542. */
  14543. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14544. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14545. };
  14546. /**
  14547. * Sets the current alpha mode
  14548. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14549. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14550. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14551. */
  14552. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14553. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14554. if (this._alphaMode === mode) {
  14555. return;
  14556. }
  14557. switch (mode) {
  14558. case Engine.ALPHA_DISABLE:
  14559. this._alphaState.alphaBlend = false;
  14560. break;
  14561. case Engine.ALPHA_PREMULTIPLIED:
  14562. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14563. this._alphaState.alphaBlend = true;
  14564. break;
  14565. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14566. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14567. this._alphaState.alphaBlend = true;
  14568. break;
  14569. case Engine.ALPHA_COMBINE:
  14570. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14571. this._alphaState.alphaBlend = true;
  14572. break;
  14573. case Engine.ALPHA_ONEONE:
  14574. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14575. this._alphaState.alphaBlend = true;
  14576. break;
  14577. case Engine.ALPHA_ADD:
  14578. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14579. this._alphaState.alphaBlend = true;
  14580. break;
  14581. case Engine.ALPHA_SUBTRACT:
  14582. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14583. this._alphaState.alphaBlend = true;
  14584. break;
  14585. case Engine.ALPHA_MULTIPLY:
  14586. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14587. this._alphaState.alphaBlend = true;
  14588. break;
  14589. case Engine.ALPHA_MAXIMIZED:
  14590. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14591. this._alphaState.alphaBlend = true;
  14592. break;
  14593. case Engine.ALPHA_INTERPOLATE:
  14594. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14595. this._alphaState.alphaBlend = true;
  14596. break;
  14597. case Engine.ALPHA_SCREENMODE:
  14598. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14599. this._alphaState.alphaBlend = true;
  14600. break;
  14601. }
  14602. if (!noDepthWriteChange) {
  14603. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14604. }
  14605. this._alphaMode = mode;
  14606. };
  14607. /**
  14608. * Gets the current alpha mode
  14609. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14610. * @returns the current alpha mode
  14611. */
  14612. Engine.prototype.getAlphaMode = function () {
  14613. return this._alphaMode;
  14614. };
  14615. // Textures
  14616. /**
  14617. * Clears the list of texture accessible through engine.
  14618. * This can help preventing texture load conflict due to name collision.
  14619. */
  14620. Engine.prototype.clearInternalTexturesCache = function () {
  14621. this._internalTexturesCache = [];
  14622. };
  14623. /**
  14624. * Force the entire cache to be cleared
  14625. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14626. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14627. */
  14628. Engine.prototype.wipeCaches = function (bruteForce) {
  14629. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14630. return;
  14631. }
  14632. this._currentEffect = null;
  14633. this._unpackFlipYCached = null;
  14634. this._viewportCached.x = 0;
  14635. this._viewportCached.y = 0;
  14636. this._viewportCached.z = 0;
  14637. this._viewportCached.w = 0;
  14638. if (bruteForce) {
  14639. this.resetTextureCache();
  14640. this._currentProgram = null;
  14641. this._stencilState.reset();
  14642. this._depthCullingState.reset();
  14643. this.setDepthFunctionToLessOrEqual();
  14644. this._alphaState.reset();
  14645. }
  14646. this._resetVertexBufferBinding();
  14647. this._cachedIndexBuffer = null;
  14648. this._cachedEffectForVertexBuffers = null;
  14649. this._unbindVertexArrayObject();
  14650. this.bindIndexBuffer(null);
  14651. };
  14652. /**
  14653. * Set the compressed texture format to use, based on the formats you have, and the formats
  14654. * supported by the hardware / browser.
  14655. *
  14656. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14657. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14658. * to API arguments needed to compressed textures. This puts the burden on the container
  14659. * generator to house the arcane code for determining these for current & future formats.
  14660. *
  14661. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14662. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14663. *
  14664. * Note: The result of this call is not taken into account when a texture is base64.
  14665. *
  14666. * @param formatsAvailable defines the list of those format families you have created
  14667. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14668. *
  14669. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14670. * @returns The extension selected.
  14671. */
  14672. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14673. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14674. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14675. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14676. return this._textureFormatInUse = this._texturesSupported[i];
  14677. }
  14678. }
  14679. }
  14680. // actively set format to nothing, to allow this to be called more than once
  14681. // and possibly fail the 2nd time
  14682. this._textureFormatInUse = null;
  14683. return null;
  14684. };
  14685. /** @hidden */
  14686. Engine.prototype._createTexture = function () {
  14687. var texture = this._gl.createTexture();
  14688. if (!texture) {
  14689. throw new Error("Unable to create texture");
  14690. }
  14691. return texture;
  14692. };
  14693. /**
  14694. * Usually called from BABYLON.Texture.ts.
  14695. * Passed information to create a WebGLTexture
  14696. * @param urlArg defines a value which contains one of the following:
  14697. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14698. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14699. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14700. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14701. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14702. * @param scene needed for loading to the correct scene
  14703. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14704. * @param onLoad optional callback to be called upon successful completion
  14705. * @param onError optional callback to be called upon failure
  14706. * @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
  14707. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14708. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14709. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14710. */
  14711. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14712. var _this = this;
  14713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14714. if (onLoad === void 0) { onLoad = null; }
  14715. if (onError === void 0) { onError = null; }
  14716. if (buffer === void 0) { buffer = null; }
  14717. if (fallback === void 0) { fallback = null; }
  14718. if (format === void 0) { format = null; }
  14719. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14720. var fromData = url.substr(0, 5) === "data:";
  14721. var fromBlob = url.substr(0, 5) === "blob:";
  14722. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14723. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14724. // establish the file extension, if possible
  14725. var lastDot = url.lastIndexOf('.');
  14726. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14727. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14728. var isTGA = (extension.indexOf(".tga") === 0);
  14729. // determine if a ktx file should be substituted
  14730. var isKTX = false;
  14731. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14732. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14733. isKTX = true;
  14734. }
  14735. if (scene) {
  14736. scene._addPendingData(texture);
  14737. }
  14738. texture.url = url;
  14739. texture.generateMipMaps = !noMipmap;
  14740. texture.samplingMode = samplingMode;
  14741. texture.invertY = invertY;
  14742. if (!this._doNotHandleContextLost) {
  14743. // Keep a link to the buffer only if we plan to handle context lost
  14744. texture._buffer = buffer;
  14745. }
  14746. var onLoadObserver = null;
  14747. if (onLoad && !fallback) {
  14748. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14749. }
  14750. if (!fallback)
  14751. this._internalTexturesCache.push(texture);
  14752. var onerror = function (message, exception) {
  14753. if (scene) {
  14754. scene._removePendingData(texture);
  14755. }
  14756. if (onLoadObserver && !isKTX) {
  14757. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14758. texture.onLoadedObservable.remove(onLoadObserver);
  14759. }
  14760. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14761. if (isKTX) {
  14762. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14763. }
  14764. else if (BABYLON.Tools.UseFallbackTexture) {
  14765. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14766. }
  14767. if (onError) {
  14768. onError(message || "Unknown error", exception);
  14769. }
  14770. };
  14771. var callback = null;
  14772. // processing for non-image formats
  14773. if (isKTX || isTGA || isDDS) {
  14774. if (isKTX) {
  14775. callback = function (data) {
  14776. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14777. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14778. ktx.uploadLevels(_this._gl, !noMipmap);
  14779. return false;
  14780. }, samplingMode);
  14781. };
  14782. }
  14783. else if (isTGA) {
  14784. callback = function (arrayBuffer) {
  14785. var data = new Uint8Array(arrayBuffer);
  14786. var header = BABYLON.TGATools.GetTGAHeader(data);
  14787. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14788. BABYLON.TGATools.UploadContent(_this._gl, data);
  14789. return false;
  14790. }, samplingMode);
  14791. };
  14792. }
  14793. else if (isDDS) {
  14794. callback = function (data) {
  14795. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14796. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14797. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14798. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14799. return false;
  14800. }, samplingMode);
  14801. };
  14802. }
  14803. if (!buffer) {
  14804. this._loadFile(url, function (data) {
  14805. if (callback) {
  14806. callback(data);
  14807. }
  14808. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14809. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14810. });
  14811. }
  14812. else {
  14813. if (callback) {
  14814. callback(buffer);
  14815. }
  14816. }
  14817. // image format processing
  14818. }
  14819. else {
  14820. var onload = function (img) {
  14821. if (fromBlob && !_this._doNotHandleContextLost) {
  14822. // We need to store the image if we need to rebuild the texture
  14823. // in case of a webgl context lost
  14824. texture._buffer = img;
  14825. }
  14826. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14827. var gl = _this._gl;
  14828. var isPot = (img.width === potWidth && img.height === potHeight);
  14829. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14830. if (isPot) {
  14831. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14832. return false;
  14833. }
  14834. var maxTextureSize = _this._caps.maxTextureSize;
  14835. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14836. _this._prepareWorkingCanvas();
  14837. if (!_this._workingCanvas || !_this._workingContext) {
  14838. return false;
  14839. }
  14840. _this._workingCanvas.width = potWidth;
  14841. _this._workingCanvas.height = potHeight;
  14842. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14843. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14844. texture.width = potWidth;
  14845. texture.height = potHeight;
  14846. return false;
  14847. }
  14848. else {
  14849. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14850. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14851. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14852. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14857. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14858. _this._releaseTexture(source_1);
  14859. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14860. continuationCallback();
  14861. });
  14862. }
  14863. return true;
  14864. }, samplingMode);
  14865. };
  14866. if (!fromData || isBase64) {
  14867. if (buffer instanceof HTMLImageElement) {
  14868. onload(buffer);
  14869. }
  14870. else {
  14871. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14872. }
  14873. }
  14874. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14875. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14876. }
  14877. else {
  14878. onload(buffer);
  14879. }
  14880. }
  14881. return texture;
  14882. };
  14883. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14884. var _this = this;
  14885. var rtt = this.createRenderTargetTexture({
  14886. width: destination.width,
  14887. height: destination.height,
  14888. }, {
  14889. generateMipMaps: false,
  14890. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14891. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14892. generateDepthBuffer: false,
  14893. generateStencilBuffer: false
  14894. });
  14895. if (!this._rescalePostProcess) {
  14896. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14897. }
  14898. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14899. _this._rescalePostProcess.onApply = function (effect) {
  14900. effect._bindTexture("textureSampler", source);
  14901. };
  14902. var hostingScene = scene;
  14903. if (!hostingScene) {
  14904. hostingScene = _this.scenes[_this.scenes.length - 1];
  14905. }
  14906. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14907. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14908. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14909. _this.unBindFramebuffer(rtt);
  14910. _this._releaseTexture(rtt);
  14911. if (onComplete) {
  14912. onComplete();
  14913. }
  14914. });
  14915. };
  14916. /**
  14917. * Update a raw texture
  14918. * @param texture defines the texture to update
  14919. * @param data defines the data to store in the texture
  14920. * @param format defines the format of the data
  14921. * @param invertY defines if data must be stored with Y axis inverted
  14922. * @param compression defines the compression used (null by default)
  14923. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14924. */
  14925. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14926. if (compression === void 0) { compression = null; }
  14927. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14928. if (!texture) {
  14929. return;
  14930. }
  14931. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14932. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14933. // babylon's internalFormat but gl's texImage2D format
  14934. var internalFormat = this._getInternalFormat(format);
  14935. var textureType = this._getWebGLTextureType(type);
  14936. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14937. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14938. if (!this._doNotHandleContextLost) {
  14939. texture._bufferView = data;
  14940. texture.format = format;
  14941. texture.type = type;
  14942. texture.invertY = invertY;
  14943. texture._compression = compression;
  14944. }
  14945. if (texture.width % 4 !== 0) {
  14946. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14947. }
  14948. if (compression && data) {
  14949. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14950. }
  14951. else {
  14952. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14953. }
  14954. if (texture.generateMipMaps) {
  14955. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14956. }
  14957. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14958. // this.resetTextureCache();
  14959. texture.isReady = true;
  14960. };
  14961. /**
  14962. * Creates a raw texture
  14963. * @param data defines the data to store in the texture
  14964. * @param width defines the width of the texture
  14965. * @param height defines the height of the texture
  14966. * @param format defines the format of the data
  14967. * @param generateMipMaps defines if the engine should generate the mip levels
  14968. * @param invertY defines if data must be stored with Y axis inverted
  14969. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14970. * @param compression defines the compression used (null by default)
  14971. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14972. * @returns the raw texture inside an InternalTexture
  14973. */
  14974. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14975. if (compression === void 0) { compression = null; }
  14976. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14977. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14978. texture.baseWidth = width;
  14979. texture.baseHeight = height;
  14980. texture.width = width;
  14981. texture.height = height;
  14982. texture.format = format;
  14983. texture.generateMipMaps = generateMipMaps;
  14984. texture.samplingMode = samplingMode;
  14985. texture.invertY = invertY;
  14986. texture._compression = compression;
  14987. texture.type = type;
  14988. if (!this._doNotHandleContextLost) {
  14989. texture._bufferView = data;
  14990. }
  14991. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14993. // Filters
  14994. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14997. if (generateMipMaps) {
  14998. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14999. }
  15000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15001. this._internalTexturesCache.push(texture);
  15002. return texture;
  15003. };
  15004. /** @hidden */
  15005. Engine.prototype._unpackFlipY = function (value) {
  15006. if (this._unpackFlipYCached !== value) {
  15007. this._unpackFlipYCached = value;
  15008. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15009. }
  15010. };
  15011. /**
  15012. * Creates a dynamic texture
  15013. * @param width defines the width of the texture
  15014. * @param height defines the height of the texture
  15015. * @param generateMipMaps defines if the engine should generate the mip levels
  15016. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15017. * @returns the dynamic texture inside an InternalTexture
  15018. */
  15019. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15020. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15021. texture.baseWidth = width;
  15022. texture.baseHeight = height;
  15023. if (generateMipMaps) {
  15024. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15025. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15026. }
  15027. // this.resetTextureCache();
  15028. texture.width = width;
  15029. texture.height = height;
  15030. texture.isReady = false;
  15031. texture.generateMipMaps = generateMipMaps;
  15032. texture.samplingMode = samplingMode;
  15033. this.updateTextureSamplingMode(samplingMode, texture);
  15034. this._internalTexturesCache.push(texture);
  15035. return texture;
  15036. };
  15037. /**
  15038. * Update the sampling mode of a given texture
  15039. * @param samplingMode defines the required sampling mode
  15040. * @param texture defines the texture to update
  15041. */
  15042. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15043. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15044. if (texture.isCube) {
  15045. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15046. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15047. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15048. }
  15049. else if (texture.is3D) {
  15050. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15051. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15052. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15053. }
  15054. else {
  15055. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15056. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15057. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15058. }
  15059. texture.samplingMode = samplingMode;
  15060. };
  15061. /**
  15062. * Update the content of a dynamic texture
  15063. * @param texture defines the texture to update
  15064. * @param canvas defines the canvas containing the source
  15065. * @param invertY defines if data must be stored with Y axis inverted
  15066. * @param premulAlpha defines if alpha is stored as premultiplied
  15067. * @param format defines the format of the data
  15068. */
  15069. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15070. if (premulAlpha === void 0) { premulAlpha = false; }
  15071. if (!texture) {
  15072. return;
  15073. }
  15074. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15075. this._unpackFlipY(invertY);
  15076. if (premulAlpha) {
  15077. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15078. }
  15079. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15080. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15081. if (texture.generateMipMaps) {
  15082. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15083. }
  15084. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15085. if (premulAlpha) {
  15086. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15087. }
  15088. texture.isReady = true;
  15089. };
  15090. /**
  15091. * Update a video texture
  15092. * @param texture defines the texture to update
  15093. * @param video defines the video element to use
  15094. * @param invertY defines if data must be stored with Y axis inverted
  15095. */
  15096. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15097. if (!texture || texture._isDisabled) {
  15098. return;
  15099. }
  15100. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15101. this._unpackFlipY(!invertY); // Video are upside down by default
  15102. try {
  15103. // Testing video texture support
  15104. if (this._videoTextureSupported === undefined) {
  15105. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15106. if (this._gl.getError() !== 0) {
  15107. this._videoTextureSupported = false;
  15108. }
  15109. else {
  15110. this._videoTextureSupported = true;
  15111. }
  15112. }
  15113. // Copy video through the current working canvas if video texture is not supported
  15114. if (!this._videoTextureSupported) {
  15115. if (!texture._workingCanvas) {
  15116. texture._workingCanvas = document.createElement("canvas");
  15117. var context = texture._workingCanvas.getContext("2d");
  15118. if (!context) {
  15119. throw new Error("Unable to get 2d context");
  15120. }
  15121. texture._workingContext = context;
  15122. texture._workingCanvas.width = texture.width;
  15123. texture._workingCanvas.height = texture.height;
  15124. }
  15125. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15126. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15127. }
  15128. else {
  15129. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15130. }
  15131. if (texture.generateMipMaps) {
  15132. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15133. }
  15134. if (!wasPreviouslyBound) {
  15135. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15136. }
  15137. // this.resetTextureCache();
  15138. texture.isReady = true;
  15139. }
  15140. catch (ex) {
  15141. // Something unexpected
  15142. // Let's disable the texture
  15143. texture._isDisabled = true;
  15144. }
  15145. };
  15146. /**
  15147. * Updates a depth texture Comparison Mode and Function.
  15148. * If the comparison Function is equal to 0, the mode will be set to none.
  15149. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15150. * @param texture The texture to set the comparison function for
  15151. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15152. */
  15153. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15154. if (this.webGLVersion === 1) {
  15155. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15156. return;
  15157. }
  15158. var gl = this._gl;
  15159. if (texture.isCube) {
  15160. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15161. if (comparisonFunction === 0) {
  15162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15164. }
  15165. else {
  15166. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15167. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15168. }
  15169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15170. }
  15171. else {
  15172. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15173. if (comparisonFunction === 0) {
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15176. }
  15177. else {
  15178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15180. }
  15181. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15182. }
  15183. texture._comparisonFunction = comparisonFunction;
  15184. };
  15185. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15186. var width = size.width || size;
  15187. var height = size.height || size;
  15188. internalTexture.baseWidth = width;
  15189. internalTexture.baseHeight = height;
  15190. internalTexture.width = width;
  15191. internalTexture.height = height;
  15192. internalTexture.isReady = true;
  15193. internalTexture.samples = 1;
  15194. internalTexture.generateMipMaps = false;
  15195. internalTexture._generateDepthBuffer = true;
  15196. internalTexture._generateStencilBuffer = generateStencil;
  15197. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15198. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15199. internalTexture._comparisonFunction = comparisonFunction;
  15200. var gl = this._gl;
  15201. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15202. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15203. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15204. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15205. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15206. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15207. if (comparisonFunction === 0) {
  15208. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15209. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15210. }
  15211. else {
  15212. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15213. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15214. }
  15215. };
  15216. /**
  15217. * Creates a depth stencil texture.
  15218. * This is only available in WebGL 2 or with the depth texture extension available.
  15219. * @param size The size of face edge in the texture.
  15220. * @param options The options defining the texture.
  15221. * @returns The texture
  15222. */
  15223. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15224. if (options.isCube) {
  15225. var width = size.width || size;
  15226. return this._createDepthStencilCubeTexture(width, options);
  15227. }
  15228. else {
  15229. return this._createDepthStencilTexture(size, options);
  15230. }
  15231. };
  15232. /**
  15233. * Creates a depth stencil texture.
  15234. * This is only available in WebGL 2 or with the depth texture extension available.
  15235. * @param size The size of face edge in the texture.
  15236. * @param options The options defining the texture.
  15237. * @returns The texture
  15238. */
  15239. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15240. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15241. if (!this._caps.depthTextureExtension) {
  15242. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15243. return internalTexture;
  15244. }
  15245. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15246. var gl = this._gl;
  15247. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15248. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15249. if (this.webGLVersion > 1) {
  15250. if (internalOptions.generateStencil) {
  15251. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15252. }
  15253. else {
  15254. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15255. }
  15256. }
  15257. else {
  15258. if (internalOptions.generateStencil) {
  15259. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15260. }
  15261. else {
  15262. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15263. }
  15264. }
  15265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15266. return internalTexture;
  15267. };
  15268. /**
  15269. * Creates a depth stencil cube texture.
  15270. * This is only available in WebGL 2.
  15271. * @param size The size of face edge in the cube texture.
  15272. * @param options The options defining the cube texture.
  15273. * @returns The cube texture
  15274. */
  15275. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15276. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15277. internalTexture.isCube = true;
  15278. if (this.webGLVersion === 1) {
  15279. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15280. return internalTexture;
  15281. }
  15282. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15283. var gl = this._gl;
  15284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15285. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15286. // Create the depth/stencil buffer
  15287. for (var face = 0; face < 6; face++) {
  15288. if (internalOptions.generateStencil) {
  15289. 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);
  15290. }
  15291. else {
  15292. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15293. }
  15294. }
  15295. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15296. return internalTexture;
  15297. };
  15298. /**
  15299. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15300. * @param renderTarget The render target to set the frame buffer for
  15301. */
  15302. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15303. // Create the framebuffer
  15304. var internalTexture = renderTarget.getInternalTexture();
  15305. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15306. return;
  15307. }
  15308. var gl = this._gl;
  15309. var depthStencilTexture = renderTarget.depthStencilTexture;
  15310. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15311. if (depthStencilTexture.isCube) {
  15312. if (depthStencilTexture._generateStencilBuffer) {
  15313. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15314. }
  15315. else {
  15316. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15317. }
  15318. }
  15319. else {
  15320. if (depthStencilTexture._generateStencilBuffer) {
  15321. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15322. }
  15323. else {
  15324. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15325. }
  15326. }
  15327. this.bindUnboundFramebuffer(null);
  15328. };
  15329. /**
  15330. * Creates a new render target texture
  15331. * @param size defines the size of the texture
  15332. * @param options defines the options used to create the texture
  15333. * @returns a new render target texture stored in an InternalTexture
  15334. */
  15335. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15336. var fullOptions = new RenderTargetCreationOptions();
  15337. if (options !== undefined && typeof options === "object") {
  15338. fullOptions.generateMipMaps = options.generateMipMaps;
  15339. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15340. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15341. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15342. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15343. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15344. }
  15345. else {
  15346. fullOptions.generateMipMaps = options;
  15347. fullOptions.generateDepthBuffer = true;
  15348. fullOptions.generateStencilBuffer = false;
  15349. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15350. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15351. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15352. }
  15353. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15354. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15355. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15356. }
  15357. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15358. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15359. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15360. }
  15361. var gl = this._gl;
  15362. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15363. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15364. var width = size.width || size;
  15365. var height = size.height || size;
  15366. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15367. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15368. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15369. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15370. }
  15371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15375. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15376. // Create the framebuffer
  15377. var currentFrameBuffer = this._currentFramebuffer;
  15378. var framebuffer = gl.createFramebuffer();
  15379. this.bindUnboundFramebuffer(framebuffer);
  15380. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15381. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15382. if (fullOptions.generateMipMaps) {
  15383. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15384. }
  15385. // Unbind
  15386. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15388. this.bindUnboundFramebuffer(currentFrameBuffer);
  15389. texture._framebuffer = framebuffer;
  15390. texture.baseWidth = width;
  15391. texture.baseHeight = height;
  15392. texture.width = width;
  15393. texture.height = height;
  15394. texture.isReady = true;
  15395. texture.samples = 1;
  15396. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15397. texture.samplingMode = fullOptions.samplingMode;
  15398. texture.type = fullOptions.type;
  15399. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15400. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15401. // this.resetTextureCache();
  15402. this._internalTexturesCache.push(texture);
  15403. return texture;
  15404. };
  15405. /**
  15406. * Create a multi render target texture
  15407. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15408. * @param size defines the size of the texture
  15409. * @param options defines the creation options
  15410. * @returns the cube texture as an InternalTexture
  15411. */
  15412. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15413. var generateMipMaps = false;
  15414. var generateDepthBuffer = true;
  15415. var generateStencilBuffer = false;
  15416. var generateDepthTexture = false;
  15417. var textureCount = 1;
  15418. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15419. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15420. var types = new Array();
  15421. var samplingModes = new Array();
  15422. if (options !== undefined) {
  15423. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15424. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15425. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15426. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15427. textureCount = options.textureCount || 1;
  15428. if (options.types) {
  15429. types = options.types;
  15430. }
  15431. if (options.samplingModes) {
  15432. samplingModes = options.samplingModes;
  15433. }
  15434. }
  15435. var gl = this._gl;
  15436. // Create the framebuffer
  15437. var framebuffer = gl.createFramebuffer();
  15438. this.bindUnboundFramebuffer(framebuffer);
  15439. var width = size.width || size;
  15440. var height = size.height || size;
  15441. var textures = [];
  15442. var attachments = [];
  15443. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15444. for (var i = 0; i < textureCount; i++) {
  15445. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15446. var type = types[i] || defaultType;
  15447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15448. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15449. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15450. }
  15451. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15452. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15453. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15454. }
  15455. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15456. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15457. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15458. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15459. }
  15460. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15461. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15462. textures.push(texture);
  15463. attachments.push(attachment);
  15464. gl.activeTexture(gl["TEXTURE" + i]);
  15465. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15470. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15471. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15472. if (generateMipMaps) {
  15473. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15474. }
  15475. // Unbind
  15476. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15477. texture._framebuffer = framebuffer;
  15478. texture._depthStencilBuffer = depthStencilBuffer;
  15479. texture.baseWidth = width;
  15480. texture.baseHeight = height;
  15481. texture.width = width;
  15482. texture.height = height;
  15483. texture.isReady = true;
  15484. texture.samples = 1;
  15485. texture.generateMipMaps = generateMipMaps;
  15486. texture.samplingMode = samplingMode;
  15487. texture.type = type;
  15488. texture._generateDepthBuffer = generateDepthBuffer;
  15489. texture._generateStencilBuffer = generateStencilBuffer;
  15490. texture._attachments = attachments;
  15491. this._internalTexturesCache.push(texture);
  15492. }
  15493. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15494. // Depth texture
  15495. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15496. gl.activeTexture(gl.TEXTURE0);
  15497. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15502. 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);
  15503. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15504. depthTexture._framebuffer = framebuffer;
  15505. depthTexture.baseWidth = width;
  15506. depthTexture.baseHeight = height;
  15507. depthTexture.width = width;
  15508. depthTexture.height = height;
  15509. depthTexture.isReady = true;
  15510. depthTexture.samples = 1;
  15511. depthTexture.generateMipMaps = generateMipMaps;
  15512. depthTexture.samplingMode = gl.NEAREST;
  15513. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15514. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15515. textures.push(depthTexture);
  15516. this._internalTexturesCache.push(depthTexture);
  15517. }
  15518. gl.drawBuffers(attachments);
  15519. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15520. this.bindUnboundFramebuffer(null);
  15521. this.resetTextureCache();
  15522. return textures;
  15523. };
  15524. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15525. if (samples === void 0) { samples = 1; }
  15526. var depthStencilBuffer = null;
  15527. var gl = this._gl;
  15528. // Create the depth/stencil buffer
  15529. if (generateStencilBuffer) {
  15530. depthStencilBuffer = gl.createRenderbuffer();
  15531. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15532. if (samples > 1) {
  15533. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15534. }
  15535. else {
  15536. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15537. }
  15538. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15539. }
  15540. else if (generateDepthBuffer) {
  15541. depthStencilBuffer = gl.createRenderbuffer();
  15542. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15543. if (samples > 1) {
  15544. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15545. }
  15546. else {
  15547. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15548. }
  15549. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15550. }
  15551. return depthStencilBuffer;
  15552. };
  15553. /**
  15554. * Updates the sample count of a render target texture
  15555. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15556. * @param texture defines the texture to update
  15557. * @param samples defines the sample count to set
  15558. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15559. */
  15560. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15561. if (this.webGLVersion < 2 || !texture) {
  15562. return 1;
  15563. }
  15564. if (texture.samples === samples) {
  15565. return samples;
  15566. }
  15567. var gl = this._gl;
  15568. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15569. // Dispose previous render buffers
  15570. if (texture._depthStencilBuffer) {
  15571. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15572. texture._depthStencilBuffer = null;
  15573. }
  15574. if (texture._MSAAFramebuffer) {
  15575. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15576. texture._MSAAFramebuffer = null;
  15577. }
  15578. if (texture._MSAARenderBuffer) {
  15579. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15580. texture._MSAARenderBuffer = null;
  15581. }
  15582. if (samples > 1) {
  15583. var framebuffer = gl.createFramebuffer();
  15584. if (!framebuffer) {
  15585. throw new Error("Unable to create multi sampled framebuffer");
  15586. }
  15587. texture._MSAAFramebuffer = framebuffer;
  15588. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15589. var colorRenderbuffer = gl.createRenderbuffer();
  15590. if (!colorRenderbuffer) {
  15591. throw new Error("Unable to create multi sampled framebuffer");
  15592. }
  15593. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15594. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15595. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15596. texture._MSAARenderBuffer = colorRenderbuffer;
  15597. }
  15598. else {
  15599. this.bindUnboundFramebuffer(texture._framebuffer);
  15600. }
  15601. texture.samples = samples;
  15602. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15603. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15604. this.bindUnboundFramebuffer(null);
  15605. return samples;
  15606. };
  15607. /**
  15608. * Update the sample count for a given multiple render target texture
  15609. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15610. * @param textures defines the textures to update
  15611. * @param samples defines the sample count to set
  15612. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15613. */
  15614. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15615. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15616. return 1;
  15617. }
  15618. if (textures[0].samples === samples) {
  15619. return samples;
  15620. }
  15621. var gl = this._gl;
  15622. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15623. // Dispose previous render buffers
  15624. if (textures[0]._depthStencilBuffer) {
  15625. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15626. textures[0]._depthStencilBuffer = null;
  15627. }
  15628. if (textures[0]._MSAAFramebuffer) {
  15629. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15630. textures[0]._MSAAFramebuffer = null;
  15631. }
  15632. for (var i = 0; i < textures.length; i++) {
  15633. if (textures[i]._MSAARenderBuffer) {
  15634. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15635. textures[i]._MSAARenderBuffer = null;
  15636. }
  15637. }
  15638. if (samples > 1) {
  15639. var framebuffer = gl.createFramebuffer();
  15640. if (!framebuffer) {
  15641. throw new Error("Unable to create multi sampled framebuffer");
  15642. }
  15643. this.bindUnboundFramebuffer(framebuffer);
  15644. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15645. var attachments = [];
  15646. for (var i = 0; i < textures.length; i++) {
  15647. var texture = textures[i];
  15648. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15649. var colorRenderbuffer = gl.createRenderbuffer();
  15650. if (!colorRenderbuffer) {
  15651. throw new Error("Unable to create multi sampled framebuffer");
  15652. }
  15653. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15654. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15655. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15656. texture._MSAAFramebuffer = framebuffer;
  15657. texture._MSAARenderBuffer = colorRenderbuffer;
  15658. texture.samples = samples;
  15659. texture._depthStencilBuffer = depthStencilBuffer;
  15660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15661. attachments.push(attachment);
  15662. }
  15663. gl.drawBuffers(attachments);
  15664. }
  15665. else {
  15666. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15667. }
  15668. this.bindUnboundFramebuffer(null);
  15669. return samples;
  15670. };
  15671. /** @hidden */
  15672. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15673. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15674. };
  15675. /** @hidden */
  15676. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15677. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15678. };
  15679. /** @hidden */
  15680. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15681. var gl = this._gl;
  15682. var textureType = this._getWebGLTextureType(texture.type);
  15683. var format = this._getInternalFormat(texture.format);
  15684. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15685. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15686. this._bindTextureDirectly(bindTarget, texture, true);
  15687. this._unpackFlipY(texture.invertY);
  15688. var target = gl.TEXTURE_2D;
  15689. if (texture.isCube) {
  15690. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15691. }
  15692. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15693. this._bindTextureDirectly(bindTarget, null, true);
  15694. };
  15695. /**
  15696. * Creates a new render target cube texture
  15697. * @param size defines the size of the texture
  15698. * @param options defines the options used to create the texture
  15699. * @returns a new render target cube texture stored in an InternalTexture
  15700. */
  15701. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15702. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15703. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15704. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15705. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15706. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15707. }
  15708. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15709. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15710. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15711. }
  15712. var gl = this._gl;
  15713. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15715. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15716. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15717. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15718. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15719. }
  15720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15724. for (var face = 0; face < 6; face++) {
  15725. 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);
  15726. }
  15727. // Create the framebuffer
  15728. var framebuffer = gl.createFramebuffer();
  15729. this.bindUnboundFramebuffer(framebuffer);
  15730. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15731. // MipMaps
  15732. if (fullOptions.generateMipMaps) {
  15733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15734. }
  15735. // Unbind
  15736. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15737. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15738. this.bindUnboundFramebuffer(null);
  15739. texture._framebuffer = framebuffer;
  15740. texture.width = size;
  15741. texture.height = size;
  15742. texture.isReady = true;
  15743. texture.isCube = true;
  15744. texture.samples = 1;
  15745. texture.generateMipMaps = fullOptions.generateMipMaps;
  15746. texture.samplingMode = fullOptions.samplingMode;
  15747. texture.type = fullOptions.type;
  15748. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15749. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15750. this._internalTexturesCache.push(texture);
  15751. return texture;
  15752. };
  15753. /**
  15754. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15755. * @param rootUrl defines the url where the file to load is located
  15756. * @param scene defines the current scene
  15757. * @param lodScale defines scale to apply to the mip map selection
  15758. * @param lodOffset defines offset to apply to the mip map selection
  15759. * @param onLoad defines an optional callback raised when the texture is loaded
  15760. * @param onError defines an optional callback raised if there is an issue to load the texture
  15761. * @param format defines the format of the data
  15762. * @param forcedExtension defines the extension to use to pick the right loader
  15763. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15764. * @returns the cube texture as an InternalTexture
  15765. */
  15766. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15767. var _this = this;
  15768. if (onLoad === void 0) { onLoad = null; }
  15769. if (onError === void 0) { onError = null; }
  15770. if (forcedExtension === void 0) { forcedExtension = null; }
  15771. if (createPolynomials === void 0) { createPolynomials = true; }
  15772. var callback = function (loadData) {
  15773. if (!loadData) {
  15774. if (onLoad) {
  15775. onLoad(null);
  15776. }
  15777. return;
  15778. }
  15779. var texture = loadData.texture;
  15780. if (!createPolynomials) {
  15781. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15782. }
  15783. else if (loadData.info.sphericalPolynomial) {
  15784. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15785. }
  15786. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15787. if (_this._caps.textureLOD) {
  15788. // Do not add extra process if texture lod is supported.
  15789. if (onLoad) {
  15790. onLoad(texture);
  15791. }
  15792. return;
  15793. }
  15794. var mipSlices = 3;
  15795. var gl = _this._gl;
  15796. var width = loadData.width;
  15797. if (!width) {
  15798. return;
  15799. }
  15800. var textures = [];
  15801. for (var i = 0; i < mipSlices; i++) {
  15802. //compute LOD from even spacing in smoothness (matching shader calculation)
  15803. var smoothness = i / (mipSlices - 1);
  15804. var roughness = 1 - smoothness;
  15805. var minLODIndex = lodOffset; // roughness = 0
  15806. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15807. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15808. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15809. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15810. glTextureFromLod.isCube = true;
  15811. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15816. if (loadData.isDDS) {
  15817. var info = loadData.info;
  15818. var data = loadData.data;
  15819. _this._unpackFlipY(info.isCompressed);
  15820. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15821. }
  15822. else {
  15823. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15824. }
  15825. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15826. // Wrap in a base texture for easy binding.
  15827. var lodTexture = new BABYLON.BaseTexture(scene);
  15828. lodTexture.isCube = true;
  15829. lodTexture._texture = glTextureFromLod;
  15830. glTextureFromLod.isReady = true;
  15831. textures.push(lodTexture);
  15832. }
  15833. texture._lodTextureHigh = textures[2];
  15834. texture._lodTextureMid = textures[1];
  15835. texture._lodTextureLow = textures[0];
  15836. if (onLoad) {
  15837. onLoad(texture);
  15838. }
  15839. };
  15840. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15841. };
  15842. /**
  15843. * Creates a cube texture
  15844. * @param rootUrl defines the url where the files to load is located
  15845. * @param scene defines the current scene
  15846. * @param files defines the list of files to load (1 per face)
  15847. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15848. * @param onLoad defines an optional callback raised when the texture is loaded
  15849. * @param onError defines an optional callback raised if there is an issue to load the texture
  15850. * @param format defines the format of the data
  15851. * @param forcedExtension defines the extension to use to pick the right loader
  15852. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15853. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15854. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15855. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15856. * @returns the cube texture as an InternalTexture
  15857. */
  15858. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15859. var _this = this;
  15860. if (onLoad === void 0) { onLoad = null; }
  15861. if (onError === void 0) { onError = null; }
  15862. if (forcedExtension === void 0) { forcedExtension = null; }
  15863. if (createPolynomials === void 0) { createPolynomials = false; }
  15864. if (lodScale === void 0) { lodScale = 0; }
  15865. if (lodOffset === void 0) { lodOffset = 0; }
  15866. if (fallback === void 0) { fallback = null; }
  15867. var gl = this._gl;
  15868. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15869. texture.isCube = true;
  15870. texture.url = rootUrl;
  15871. texture.generateMipMaps = !noMipmap;
  15872. texture._lodGenerationScale = lodScale;
  15873. texture._lodGenerationOffset = lodOffset;
  15874. if (!this._doNotHandleContextLost) {
  15875. texture._extension = forcedExtension;
  15876. texture._files = files;
  15877. }
  15878. var isKTX = false;
  15879. var isDDS = false;
  15880. var isEnv = false;
  15881. var lastDot = rootUrl.lastIndexOf('.');
  15882. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15883. if (this._textureFormatInUse && !fallback) {
  15884. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15885. isKTX = true;
  15886. }
  15887. else {
  15888. isDDS = (extension === ".dds");
  15889. isEnv = (extension === ".env");
  15890. }
  15891. var onerror = function (request, exception) {
  15892. if (isKTX) {
  15893. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15894. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15895. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15896. }
  15897. if (onError && request) {
  15898. onError(request.status + " " + request.statusText, exception);
  15899. }
  15900. };
  15901. if (isKTX) {
  15902. this._loadFile(rootUrl, function (data) {
  15903. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15904. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15906. _this._unpackFlipY(true);
  15907. ktx.uploadLevels(_this._gl, !noMipmap);
  15908. _this.setCubeMapTextureParams(gl, loadMipmap);
  15909. texture.width = ktx.pixelWidth;
  15910. texture.height = ktx.pixelHeight;
  15911. texture.isReady = true;
  15912. }, undefined, undefined, true, onerror);
  15913. }
  15914. else if (isEnv) {
  15915. this._loadFile(rootUrl, function (data) {
  15916. data = data;
  15917. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15918. if (info) {
  15919. texture.width = info.width;
  15920. texture.height = info.width;
  15921. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15922. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15923. texture.isReady = true;
  15924. if (onLoad) {
  15925. onLoad();
  15926. }
  15927. });
  15928. }
  15929. else if (onError) {
  15930. onError("Can not parse the environment file", null);
  15931. }
  15932. }, undefined, undefined, true, onerror);
  15933. }
  15934. else if (isDDS) {
  15935. if (files && files.length === 6) {
  15936. this._cascadeLoadFiles(scene, function (imgs) {
  15937. var info;
  15938. var loadMipmap = false;
  15939. var width = 0;
  15940. for (var index = 0; index < imgs.length; index++) {
  15941. var data = imgs[index];
  15942. info = BABYLON.DDSTools.GetDDSInfo(data);
  15943. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15945. _this._unpackFlipY(info.isCompressed);
  15946. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15947. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15948. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15949. }
  15950. texture.width = info.width;
  15951. texture.height = info.height;
  15952. texture.type = info.textureType;
  15953. width = info.width;
  15954. }
  15955. _this.setCubeMapTextureParams(gl, loadMipmap);
  15956. texture.isReady = true;
  15957. if (onLoad) {
  15958. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15959. }
  15960. }, files, onError);
  15961. }
  15962. else {
  15963. this._loadFile(rootUrl, function (data) {
  15964. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15965. if (createPolynomials) {
  15966. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15967. }
  15968. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15969. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15970. _this._unpackFlipY(info.isCompressed);
  15971. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15972. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15973. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15974. }
  15975. _this.setCubeMapTextureParams(gl, loadMipmap);
  15976. texture.width = info.width;
  15977. texture.height = info.height;
  15978. texture.isReady = true;
  15979. texture.type = info.textureType;
  15980. if (onLoad) {
  15981. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15982. }
  15983. }, undefined, undefined, true, onerror);
  15984. }
  15985. }
  15986. else {
  15987. if (!files) {
  15988. throw new Error("Cannot load cubemap because files were not defined");
  15989. }
  15990. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15991. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15992. var height = width;
  15993. _this._prepareWorkingCanvas();
  15994. if (!_this._workingCanvas || !_this._workingContext) {
  15995. return;
  15996. }
  15997. _this._workingCanvas.width = width;
  15998. _this._workingCanvas.height = height;
  15999. var faces = [
  16000. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16001. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16002. ];
  16003. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16004. _this._unpackFlipY(false);
  16005. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16006. for (var index = 0; index < faces.length; index++) {
  16007. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16008. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16009. }
  16010. if (!noMipmap) {
  16011. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16012. }
  16013. _this.setCubeMapTextureParams(gl, !noMipmap);
  16014. texture.width = width;
  16015. texture.height = height;
  16016. texture.isReady = true;
  16017. if (format) {
  16018. texture.format = format;
  16019. }
  16020. texture.onLoadedObservable.notifyObservers(texture);
  16021. texture.onLoadedObservable.clear();
  16022. if (onLoad) {
  16023. onLoad();
  16024. }
  16025. }, files, onError);
  16026. }
  16027. this._internalTexturesCache.push(texture);
  16028. return texture;
  16029. };
  16030. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16033. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16035. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16036. // this.resetTextureCache();
  16037. };
  16038. /**
  16039. * Update a raw cube texture
  16040. * @param texture defines the texture to udpdate
  16041. * @param data defines the data to store
  16042. * @param format defines the data format
  16043. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16044. * @param invertY defines if data must be stored with Y axis inverted
  16045. * @param compression defines the compression used (null by default)
  16046. * @param level defines which level of the texture to update
  16047. */
  16048. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16049. if (compression === void 0) { compression = null; }
  16050. if (level === void 0) { level = 0; }
  16051. texture._bufferViewArray = data;
  16052. texture.format = format;
  16053. texture.type = type;
  16054. texture.invertY = invertY;
  16055. texture._compression = compression;
  16056. var gl = this._gl;
  16057. var textureType = this._getWebGLTextureType(type);
  16058. var internalFormat = this._getInternalFormat(format);
  16059. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16060. var needConversion = false;
  16061. if (internalFormat === gl.RGB) {
  16062. internalFormat = gl.RGBA;
  16063. needConversion = true;
  16064. }
  16065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16066. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16067. if (texture.width % 4 !== 0) {
  16068. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16069. }
  16070. // Data are known to be in +X +Y +Z -X -Y -Z
  16071. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16072. var faceData = data[faceIndex];
  16073. if (compression) {
  16074. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16075. }
  16076. else {
  16077. if (needConversion) {
  16078. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16079. }
  16080. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16081. }
  16082. }
  16083. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16084. if (isPot && texture.generateMipMaps && level === 0) {
  16085. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16086. }
  16087. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16088. // this.resetTextureCache();
  16089. texture.isReady = true;
  16090. };
  16091. /**
  16092. * Creates a new raw cube texture
  16093. * @param data defines the array of data to use to create each face
  16094. * @param size defines the size of the textures
  16095. * @param format defines the format of the data
  16096. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16097. * @param generateMipMaps defines if the engine should generate the mip levels
  16098. * @param invertY defines if data must be stored with Y axis inverted
  16099. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16100. * @param compression defines the compression used (null by default)
  16101. * @returns the cube texture as an InternalTexture
  16102. */
  16103. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16104. if (compression === void 0) { compression = null; }
  16105. var gl = this._gl;
  16106. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16107. texture.isCube = true;
  16108. texture.generateMipMaps = generateMipMaps;
  16109. texture.format = format;
  16110. texture.type = type;
  16111. if (!this._doNotHandleContextLost) {
  16112. texture._bufferViewArray = data;
  16113. }
  16114. var textureType = this._getWebGLTextureType(type);
  16115. var internalFormat = this._getInternalFormat(format);
  16116. if (internalFormat === gl.RGB) {
  16117. internalFormat = gl.RGBA;
  16118. }
  16119. var width = size;
  16120. var height = width;
  16121. texture.width = width;
  16122. texture.height = height;
  16123. // Double check on POT to generate Mips.
  16124. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16125. if (!isPot) {
  16126. generateMipMaps = false;
  16127. }
  16128. // Upload data if needed. The texture won't be ready until then.
  16129. if (data) {
  16130. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16131. }
  16132. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16133. // Filters
  16134. if (data && generateMipMaps) {
  16135. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16136. }
  16137. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16140. }
  16141. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16144. }
  16145. else {
  16146. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16149. }
  16150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16152. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16153. return texture;
  16154. };
  16155. /**
  16156. * Creates a new raw cube texture from a specified url
  16157. * @param url defines the url where the data is located
  16158. * @param scene defines the current scene
  16159. * @param size defines the size of the textures
  16160. * @param format defines the format of the data
  16161. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16162. * @param noMipmap defines if the engine should avoid generating the mip levels
  16163. * @param callback defines a callback used to extract texture data from loaded data
  16164. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16165. * @param onLoad defines a callback called when texture is loaded
  16166. * @param onError defines a callback called if there is an error
  16167. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16168. * @param invertY defines if data must be stored with Y axis inverted
  16169. * @returns the cube texture as an InternalTexture
  16170. */
  16171. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16172. var _this = this;
  16173. if (onLoad === void 0) { onLoad = null; }
  16174. if (onError === void 0) { onError = null; }
  16175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16176. if (invertY === void 0) { invertY = false; }
  16177. var gl = this._gl;
  16178. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16179. scene._addPendingData(texture);
  16180. texture.url = url;
  16181. this._internalTexturesCache.push(texture);
  16182. var onerror = function (request, exception) {
  16183. scene._removePendingData(texture);
  16184. if (onError && request) {
  16185. onError(request.status + " " + request.statusText, exception);
  16186. }
  16187. };
  16188. var internalCallback = function (data) {
  16189. var width = texture.width;
  16190. var faceDataArrays = callback(data);
  16191. if (!faceDataArrays) {
  16192. return;
  16193. }
  16194. if (mipmapGenerator) {
  16195. var textureType = _this._getWebGLTextureType(type);
  16196. var internalFormat = _this._getInternalFormat(format);
  16197. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16198. var needConversion = false;
  16199. if (internalFormat === gl.RGB) {
  16200. internalFormat = gl.RGBA;
  16201. needConversion = true;
  16202. }
  16203. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16204. _this._unpackFlipY(false);
  16205. var mipData = mipmapGenerator(faceDataArrays);
  16206. for (var level = 0; level < mipData.length; level++) {
  16207. var mipSize = width >> level;
  16208. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16209. var mipFaceData = mipData[level][faceIndex];
  16210. if (needConversion) {
  16211. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16212. }
  16213. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16214. }
  16215. }
  16216. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16217. }
  16218. else {
  16219. texture.generateMipMaps = !noMipmap;
  16220. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16221. }
  16222. texture.isReady = true;
  16223. // this.resetTextureCache();
  16224. scene._removePendingData(texture);
  16225. if (onLoad) {
  16226. onLoad();
  16227. }
  16228. };
  16229. this._loadFile(url, function (data) {
  16230. internalCallback(data);
  16231. }, undefined, scene.database, true, onerror);
  16232. return texture;
  16233. };
  16234. ;
  16235. /**
  16236. * Update a raw 3D texture
  16237. * @param texture defines the texture to update
  16238. * @param data defines the data to store
  16239. * @param format defines the data format
  16240. * @param invertY defines if data must be stored with Y axis inverted
  16241. * @param compression defines the used compression (can be null)
  16242. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16243. */
  16244. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16245. if (compression === void 0) { compression = null; }
  16246. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16247. var internalType = this._getWebGLTextureType(textureType);
  16248. var internalFormat = this._getInternalFormat(format);
  16249. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16250. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16251. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16252. if (!this._doNotHandleContextLost) {
  16253. texture._bufferView = data;
  16254. texture.format = format;
  16255. texture.invertY = invertY;
  16256. texture._compression = compression;
  16257. }
  16258. if (texture.width % 4 !== 0) {
  16259. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16260. }
  16261. if (compression && data) {
  16262. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16263. }
  16264. else {
  16265. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16266. }
  16267. if (texture.generateMipMaps) {
  16268. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16269. }
  16270. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16271. // this.resetTextureCache();
  16272. texture.isReady = true;
  16273. };
  16274. /**
  16275. * Creates a new raw 3D texture
  16276. * @param data defines the data used to create the texture
  16277. * @param width defines the width of the texture
  16278. * @param height defines the height of the texture
  16279. * @param depth defines the depth of the texture
  16280. * @param format defines the format of the texture
  16281. * @param generateMipMaps defines if the engine must generate mip levels
  16282. * @param invertY defines if data must be stored with Y axis inverted
  16283. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16284. * @param compression defines the compressed used (can be null)
  16285. * @param textureType defines the compressed used (can be null)
  16286. * @returns a new raw 3D texture (stored in an InternalTexture)
  16287. */
  16288. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16289. if (compression === void 0) { compression = null; }
  16290. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16291. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16292. texture.baseWidth = width;
  16293. texture.baseHeight = height;
  16294. texture.baseDepth = depth;
  16295. texture.width = width;
  16296. texture.height = height;
  16297. texture.depth = depth;
  16298. texture.format = format;
  16299. texture.type = textureType;
  16300. texture.generateMipMaps = generateMipMaps;
  16301. texture.samplingMode = samplingMode;
  16302. texture.is3D = true;
  16303. if (!this._doNotHandleContextLost) {
  16304. texture._bufferView = data;
  16305. }
  16306. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16307. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16308. // Filters
  16309. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16310. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16311. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16312. if (generateMipMaps) {
  16313. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16314. }
  16315. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16316. this._internalTexturesCache.push(texture);
  16317. return texture;
  16318. };
  16319. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16320. var gl = this._gl;
  16321. if (!gl) {
  16322. return;
  16323. }
  16324. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16327. if (!noMipmap && !isCompressed) {
  16328. gl.generateMipmap(gl.TEXTURE_2D);
  16329. }
  16330. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16331. // this.resetTextureCache();
  16332. if (scene) {
  16333. scene._removePendingData(texture);
  16334. }
  16335. texture.onLoadedObservable.notifyObservers(texture);
  16336. texture.onLoadedObservable.clear();
  16337. };
  16338. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16339. var _this = this;
  16340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16341. var maxTextureSize = this.getCaps().maxTextureSize;
  16342. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16343. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16344. var gl = this._gl;
  16345. if (!gl) {
  16346. return;
  16347. }
  16348. if (!texture._webGLTexture) {
  16349. // this.resetTextureCache();
  16350. if (scene) {
  16351. scene._removePendingData(texture);
  16352. }
  16353. return;
  16354. }
  16355. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16356. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16357. texture.baseWidth = width;
  16358. texture.baseHeight = height;
  16359. texture.width = potWidth;
  16360. texture.height = potHeight;
  16361. texture.isReady = true;
  16362. if (processFunction(potWidth, potHeight, function () {
  16363. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16364. })) {
  16365. // Returning as texture needs extra async steps
  16366. return;
  16367. }
  16368. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16369. };
  16370. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16371. // Create new RGBA data container.
  16372. var rgbaData;
  16373. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16374. rgbaData = new Float32Array(width * height * 4);
  16375. }
  16376. else {
  16377. rgbaData = new Uint32Array(width * height * 4);
  16378. }
  16379. // Convert each pixel.
  16380. for (var x = 0; x < width; x++) {
  16381. for (var y = 0; y < height; y++) {
  16382. var index = (y * width + x) * 3;
  16383. var newIndex = (y * width + x) * 4;
  16384. // Map Old Value to new value.
  16385. rgbaData[newIndex + 0] = rgbData[index + 0];
  16386. rgbaData[newIndex + 1] = rgbData[index + 1];
  16387. rgbaData[newIndex + 2] = rgbData[index + 2];
  16388. // Add fully opaque alpha channel.
  16389. rgbaData[newIndex + 3] = 1;
  16390. }
  16391. }
  16392. return rgbaData;
  16393. };
  16394. /** @hidden */
  16395. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16396. var gl = this._gl;
  16397. if (texture._framebuffer) {
  16398. gl.deleteFramebuffer(texture._framebuffer);
  16399. texture._framebuffer = null;
  16400. }
  16401. if (texture._depthStencilBuffer) {
  16402. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16403. texture._depthStencilBuffer = null;
  16404. }
  16405. if (texture._MSAAFramebuffer) {
  16406. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16407. texture._MSAAFramebuffer = null;
  16408. }
  16409. if (texture._MSAARenderBuffer) {
  16410. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16411. texture._MSAARenderBuffer = null;
  16412. }
  16413. };
  16414. /** @hidden */
  16415. Engine.prototype._releaseTexture = function (texture) {
  16416. var gl = this._gl;
  16417. this._releaseFramebufferObjects(texture);
  16418. gl.deleteTexture(texture._webGLTexture);
  16419. // Unbind channels
  16420. this.unbindAllTextures();
  16421. var index = this._internalTexturesCache.indexOf(texture);
  16422. if (index !== -1) {
  16423. this._internalTexturesCache.splice(index, 1);
  16424. }
  16425. // Integrated fixed lod samplers.
  16426. if (texture._lodTextureHigh) {
  16427. texture._lodTextureHigh.dispose();
  16428. }
  16429. if (texture._lodTextureMid) {
  16430. texture._lodTextureMid.dispose();
  16431. }
  16432. if (texture._lodTextureLow) {
  16433. texture._lodTextureLow.dispose();
  16434. }
  16435. // Set output texture of post process to null if the texture has been released/disposed
  16436. this.scenes.forEach(function (scene) {
  16437. scene.postProcesses.forEach(function (postProcess) {
  16438. if (postProcess._outputTexture == texture) {
  16439. postProcess._outputTexture = null;
  16440. }
  16441. });
  16442. scene.cameras.forEach(function (camera) {
  16443. camera._postProcesses.forEach(function (postProcess) {
  16444. if (postProcess) {
  16445. if (postProcess._outputTexture == texture) {
  16446. postProcess._outputTexture = null;
  16447. }
  16448. }
  16449. });
  16450. });
  16451. });
  16452. };
  16453. Engine.prototype.setProgram = function (program) {
  16454. if (this._currentProgram !== program) {
  16455. this._gl.useProgram(program);
  16456. this._currentProgram = program;
  16457. }
  16458. };
  16459. /**
  16460. * Binds an effect to the webGL context
  16461. * @param effect defines the effect to bind
  16462. */
  16463. Engine.prototype.bindSamplers = function (effect) {
  16464. this.setProgram(effect.getProgram());
  16465. var samplers = effect.getSamplers();
  16466. for (var index = 0; index < samplers.length; index++) {
  16467. var uniform = effect.getUniform(samplers[index]);
  16468. if (uniform) {
  16469. this._boundUniforms[index] = uniform;
  16470. }
  16471. }
  16472. this._currentEffect = null;
  16473. };
  16474. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16475. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16476. return;
  16477. }
  16478. // Remove
  16479. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16480. // Bind last to it
  16481. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16482. // Bind to dummy
  16483. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16484. };
  16485. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16486. if (!internalTexture) {
  16487. return -1;
  16488. }
  16489. internalTexture._initialSlot = channel;
  16490. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16491. if (channel !== internalTexture._designatedSlot) {
  16492. this._textureCollisions.addCount(1, false);
  16493. }
  16494. }
  16495. else {
  16496. if (channel !== internalTexture._designatedSlot) {
  16497. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16498. return internalTexture._designatedSlot;
  16499. }
  16500. else {
  16501. // No slot for this texture, let's pick a new one (if we find a free slot)
  16502. if (this._nextFreeTextureSlots.length) {
  16503. return this._nextFreeTextureSlots[0];
  16504. }
  16505. // We need to recycle the oldest bound texture, sorry.
  16506. this._textureCollisions.addCount(1, false);
  16507. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16508. }
  16509. }
  16510. }
  16511. return channel;
  16512. };
  16513. Engine.prototype._linkTrackers = function (previous, next) {
  16514. previous.next = next;
  16515. next.previous = previous;
  16516. };
  16517. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16518. var currentSlot = internalTexture._designatedSlot;
  16519. if (currentSlot === -1) {
  16520. return -1;
  16521. }
  16522. internalTexture._designatedSlot = -1;
  16523. if (this.disableTextureBindingOptimization) {
  16524. return -1;
  16525. }
  16526. // Remove from bound list
  16527. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16528. // Free the slot
  16529. this._boundTexturesCache[currentSlot] = null;
  16530. this._nextFreeTextureSlots.push(currentSlot);
  16531. return currentSlot;
  16532. };
  16533. Engine.prototype._activateCurrentTexture = function () {
  16534. if (this._currentTextureChannel !== this._activeChannel) {
  16535. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16536. this._currentTextureChannel = this._activeChannel;
  16537. }
  16538. };
  16539. /** @hidden */
  16540. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16541. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16542. if (force === void 0) { force = false; }
  16543. var wasPreviouslyBound = false;
  16544. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16545. this._activeChannel = texture._designatedSlot;
  16546. }
  16547. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16548. var isTextureForRendering = texture && texture._initialSlot > -1;
  16549. if (currentTextureBound !== texture || force) {
  16550. if (currentTextureBound) {
  16551. this._removeDesignatedSlot(currentTextureBound);
  16552. }
  16553. this._activateCurrentTexture();
  16554. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16555. this._boundTexturesCache[this._activeChannel] = texture;
  16556. if (texture) {
  16557. if (!this.disableTextureBindingOptimization) {
  16558. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16559. if (slotIndex > -1) {
  16560. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16561. }
  16562. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16563. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16564. }
  16565. texture._designatedSlot = this._activeChannel;
  16566. }
  16567. }
  16568. else if (forTextureDataUpdate) {
  16569. wasPreviouslyBound = true;
  16570. this._activateCurrentTexture();
  16571. }
  16572. if (isTextureForRendering && !forTextureDataUpdate) {
  16573. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16574. }
  16575. return wasPreviouslyBound;
  16576. };
  16577. /** @hidden */
  16578. Engine.prototype._bindTexture = function (channel, texture) {
  16579. if (channel < 0) {
  16580. return;
  16581. }
  16582. if (texture) {
  16583. channel = this._getCorrectTextureChannel(channel, texture);
  16584. }
  16585. this._activeChannel = channel;
  16586. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16587. };
  16588. /**
  16589. * Sets a texture to the webGL context from a postprocess
  16590. * @param channel defines the channel to use
  16591. * @param postProcess defines the source postprocess
  16592. */
  16593. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16594. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16595. };
  16596. /**
  16597. * Binds the output of the passed in post process to the texture channel specified
  16598. * @param channel The channel the texture should be bound to
  16599. * @param postProcess The post process which's output should be bound
  16600. */
  16601. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16602. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16603. };
  16604. /**
  16605. * Unbind all textures from the webGL context
  16606. */
  16607. Engine.prototype.unbindAllTextures = function () {
  16608. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16609. this._activeChannel = channel;
  16610. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16611. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16612. if (this.webGLVersion > 1) {
  16613. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16614. }
  16615. }
  16616. };
  16617. /**
  16618. * Sets a texture to the according uniform.
  16619. * @param channel The texture channel
  16620. * @param uniform The uniform to set
  16621. * @param texture The texture to apply
  16622. */
  16623. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16624. if (channel < 0) {
  16625. return;
  16626. }
  16627. if (uniform) {
  16628. this._boundUniforms[channel] = uniform;
  16629. }
  16630. this._setTexture(channel, texture);
  16631. };
  16632. /**
  16633. * Sets a depth stencil texture from a render target to the according uniform.
  16634. * @param channel The texture channel
  16635. * @param uniform The uniform to set
  16636. * @param texture The render target texture containing the depth stencil texture to apply
  16637. */
  16638. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16639. if (channel < 0) {
  16640. return;
  16641. }
  16642. if (uniform) {
  16643. this._boundUniforms[channel] = uniform;
  16644. }
  16645. if (!texture || !texture.depthStencilTexture) {
  16646. this._setTexture(channel, null);
  16647. }
  16648. else {
  16649. this._setTexture(channel, texture, false, true);
  16650. }
  16651. };
  16652. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16653. var uniform = this._boundUniforms[sourceSlot];
  16654. if (uniform._currentState === destination) {
  16655. return;
  16656. }
  16657. this._gl.uniform1i(uniform, destination);
  16658. uniform._currentState = destination;
  16659. };
  16660. Engine.prototype._getTextureWrapMode = function (mode) {
  16661. switch (mode) {
  16662. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16663. return this._gl.REPEAT;
  16664. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16665. return this._gl.CLAMP_TO_EDGE;
  16666. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16667. return this._gl.MIRRORED_REPEAT;
  16668. }
  16669. return this._gl.REPEAT;
  16670. };
  16671. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16672. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16673. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16674. // Not ready?
  16675. if (!texture) {
  16676. if (this._boundTexturesCache[channel] != null) {
  16677. this._activeChannel = channel;
  16678. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16679. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16680. if (this.webGLVersion > 1) {
  16681. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16682. }
  16683. }
  16684. return false;
  16685. }
  16686. // Video
  16687. if (texture.video) {
  16688. this._activeChannel = channel;
  16689. texture.update();
  16690. }
  16691. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16692. texture.delayLoad();
  16693. return false;
  16694. }
  16695. var internalTexture;
  16696. if (depthStencilTexture) {
  16697. internalTexture = texture.depthStencilTexture;
  16698. }
  16699. else if (texture.isReady()) {
  16700. internalTexture = texture.getInternalTexture();
  16701. }
  16702. else if (texture.isCube) {
  16703. internalTexture = this.emptyCubeTexture;
  16704. }
  16705. else if (texture.is3D) {
  16706. internalTexture = this.emptyTexture3D;
  16707. }
  16708. else {
  16709. internalTexture = this.emptyTexture;
  16710. }
  16711. if (!isPartOfTextureArray) {
  16712. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16713. }
  16714. var needToBind = true;
  16715. if (this._boundTexturesCache[channel] === internalTexture) {
  16716. this._moveBoundTextureOnTop(internalTexture);
  16717. if (!isPartOfTextureArray) {
  16718. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16719. }
  16720. needToBind = false;
  16721. }
  16722. this._activeChannel = channel;
  16723. if (internalTexture && internalTexture.is3D) {
  16724. if (needToBind) {
  16725. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16726. }
  16727. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16728. internalTexture._cachedWrapU = texture.wrapU;
  16729. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16730. }
  16731. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16732. internalTexture._cachedWrapV = texture.wrapV;
  16733. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16734. }
  16735. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16736. internalTexture._cachedWrapR = texture.wrapR;
  16737. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16738. }
  16739. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16740. }
  16741. else if (internalTexture && internalTexture.isCube) {
  16742. if (needToBind) {
  16743. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16744. }
  16745. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16746. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16747. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16748. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16749. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16750. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16751. }
  16752. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16753. }
  16754. else {
  16755. if (needToBind) {
  16756. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16757. }
  16758. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16759. internalTexture._cachedWrapU = texture.wrapU;
  16760. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16761. }
  16762. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16763. internalTexture._cachedWrapV = texture.wrapV;
  16764. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16765. }
  16766. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16767. }
  16768. return true;
  16769. };
  16770. /**
  16771. * Sets an array of texture to the webGL context
  16772. * @param channel defines the channel where the texture array must be set
  16773. * @param uniform defines the associated uniform location
  16774. * @param textures defines the array of textures to bind
  16775. */
  16776. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16777. if (channel < 0 || !uniform) {
  16778. return;
  16779. }
  16780. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16781. this._textureUnits = new Int32Array(textures.length);
  16782. }
  16783. for (var i = 0; i < textures.length; i++) {
  16784. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16785. }
  16786. this._gl.uniform1iv(uniform, this._textureUnits);
  16787. for (var index = 0; index < textures.length; index++) {
  16788. this._setTexture(this._textureUnits[index], textures[index], true);
  16789. }
  16790. };
  16791. /** @hidden */
  16792. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16793. var internalTexture = texture.getInternalTexture();
  16794. if (!internalTexture) {
  16795. return;
  16796. }
  16797. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16798. var value = texture.anisotropicFilteringLevel;
  16799. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16800. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16801. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16802. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16803. }
  16804. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16805. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16806. internalTexture._cachedAnisotropicFilteringLevel = value;
  16807. }
  16808. };
  16809. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16810. this._bindTextureDirectly(target, texture, true, true);
  16811. this._gl.texParameterf(target, parameter, value);
  16812. };
  16813. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16814. if (texture) {
  16815. this._bindTextureDirectly(target, texture, true, true);
  16816. }
  16817. this._gl.texParameteri(target, parameter, value);
  16818. };
  16819. /**
  16820. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16821. * @param x defines the x coordinate of the rectangle where pixels must be read
  16822. * @param y defines the y coordinate of the rectangle where pixels must be read
  16823. * @param width defines the width of the rectangle where pixels must be read
  16824. * @param height defines the height of the rectangle where pixels must be read
  16825. * @returns a Uint8Array containing RGBA colors
  16826. */
  16827. Engine.prototype.readPixels = function (x, y, width, height) {
  16828. var data = new Uint8Array(height * width * 4);
  16829. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16830. return data;
  16831. };
  16832. /**
  16833. * Add an externaly attached data from its key.
  16834. * This method call will fail and return false, if such key already exists.
  16835. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16836. * @param key the unique key that identifies the data
  16837. * @param data the data object to associate to the key for this Engine instance
  16838. * @return true if no such key were already present and the data was added successfully, false otherwise
  16839. */
  16840. Engine.prototype.addExternalData = function (key, data) {
  16841. if (!this._externalData) {
  16842. this._externalData = new BABYLON.StringDictionary();
  16843. }
  16844. return this._externalData.add(key, data);
  16845. };
  16846. /**
  16847. * Get an externaly attached data from its key
  16848. * @param key the unique key that identifies the data
  16849. * @return the associated data, if present (can be null), or undefined if not present
  16850. */
  16851. Engine.prototype.getExternalData = function (key) {
  16852. if (!this._externalData) {
  16853. this._externalData = new BABYLON.StringDictionary();
  16854. }
  16855. return this._externalData.get(key);
  16856. };
  16857. /**
  16858. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16859. * @param key the unique key that identifies the data
  16860. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16861. * @return the associated data, can be null if the factory returned null.
  16862. */
  16863. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16864. if (!this._externalData) {
  16865. this._externalData = new BABYLON.StringDictionary();
  16866. }
  16867. return this._externalData.getOrAddWithFactory(key, factory);
  16868. };
  16869. /**
  16870. * Remove an externaly attached data from the Engine instance
  16871. * @param key the unique key that identifies the data
  16872. * @return true if the data was successfully removed, false if it doesn't exist
  16873. */
  16874. Engine.prototype.removeExternalData = function (key) {
  16875. if (!this._externalData) {
  16876. this._externalData = new BABYLON.StringDictionary();
  16877. }
  16878. return this._externalData.remove(key);
  16879. };
  16880. /**
  16881. * Unbind all vertex attributes from the webGL context
  16882. */
  16883. Engine.prototype.unbindAllAttributes = function () {
  16884. if (this._mustWipeVertexAttributes) {
  16885. this._mustWipeVertexAttributes = false;
  16886. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16887. this._gl.disableVertexAttribArray(i);
  16888. this._vertexAttribArraysEnabled[i] = false;
  16889. this._currentBufferPointers[i].active = false;
  16890. }
  16891. return;
  16892. }
  16893. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16894. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16895. continue;
  16896. }
  16897. this._gl.disableVertexAttribArray(i);
  16898. this._vertexAttribArraysEnabled[i] = false;
  16899. this._currentBufferPointers[i].active = false;
  16900. }
  16901. };
  16902. /**
  16903. * 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
  16904. */
  16905. Engine.prototype.releaseEffects = function () {
  16906. for (var name in this._compiledEffects) {
  16907. this._deleteProgram(this._compiledEffects[name]._program);
  16908. }
  16909. this._compiledEffects = {};
  16910. };
  16911. /**
  16912. * Dispose and release all associated resources
  16913. */
  16914. Engine.prototype.dispose = function () {
  16915. this.hideLoadingUI();
  16916. this.stopRenderLoop();
  16917. // Release postProcesses
  16918. while (this.postProcesses.length) {
  16919. this.postProcesses[0].dispose();
  16920. }
  16921. // Empty texture
  16922. if (this._emptyTexture) {
  16923. this._releaseTexture(this._emptyTexture);
  16924. this._emptyTexture = null;
  16925. }
  16926. if (this._emptyCubeTexture) {
  16927. this._releaseTexture(this._emptyCubeTexture);
  16928. this._emptyCubeTexture = null;
  16929. }
  16930. // Rescale PP
  16931. if (this._rescalePostProcess) {
  16932. this._rescalePostProcess.dispose();
  16933. }
  16934. // Release scenes
  16935. while (this.scenes.length) {
  16936. this.scenes[0].dispose();
  16937. }
  16938. // Release audio engine
  16939. if (Engine.audioEngine) {
  16940. Engine.audioEngine.dispose();
  16941. }
  16942. // Release effects
  16943. this.releaseEffects();
  16944. // Unbind
  16945. this.unbindAllAttributes();
  16946. this._boundUniforms = [];
  16947. if (this._dummyFramebuffer) {
  16948. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16949. }
  16950. //WebVR
  16951. this.disableVR();
  16952. // Events
  16953. if (BABYLON.Tools.IsWindowObjectExist()) {
  16954. window.removeEventListener("blur", this._onBlur);
  16955. window.removeEventListener("focus", this._onFocus);
  16956. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16957. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16958. if (this._renderingCanvas) {
  16959. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16960. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16961. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16962. if (!this._doNotHandleContextLost) {
  16963. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16964. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16965. }
  16966. }
  16967. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16968. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16969. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16970. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16971. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16972. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16973. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16974. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16975. if (this._onVrDisplayConnect) {
  16976. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16977. if (this._onVrDisplayDisconnect) {
  16978. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16979. }
  16980. if (this._onVrDisplayPresentChange) {
  16981. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16982. }
  16983. this._onVrDisplayConnect = null;
  16984. this._onVrDisplayDisconnect = null;
  16985. }
  16986. }
  16987. // Remove from Instances
  16988. var index = Engine.Instances.indexOf(this);
  16989. if (index >= 0) {
  16990. Engine.Instances.splice(index, 1);
  16991. }
  16992. this._workingCanvas = null;
  16993. this._workingContext = null;
  16994. this._currentBufferPointers = [];
  16995. this._renderingCanvas = null;
  16996. this._currentProgram = null;
  16997. this._bindedRenderFunction = null;
  16998. this.onResizeObservable.clear();
  16999. this.onCanvasBlurObservable.clear();
  17000. this.onCanvasFocusObservable.clear();
  17001. this.onCanvasPointerOutObservable.clear();
  17002. this.onBeginFrameObservable.clear();
  17003. this.onEndFrameObservable.clear();
  17004. BABYLON.Effect.ResetCache();
  17005. // Abort active requests
  17006. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17007. var request = _a[_i];
  17008. request.abort();
  17009. }
  17010. };
  17011. // Loading screen
  17012. /**
  17013. * Display the loading screen
  17014. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17015. */
  17016. Engine.prototype.displayLoadingUI = function () {
  17017. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17018. return;
  17019. }
  17020. var loadingScreen = this.loadingScreen;
  17021. if (loadingScreen) {
  17022. loadingScreen.displayLoadingUI();
  17023. }
  17024. };
  17025. /**
  17026. * Hide the loading screen
  17027. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17028. */
  17029. Engine.prototype.hideLoadingUI = function () {
  17030. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17031. return;
  17032. }
  17033. var loadingScreen = this.loadingScreen;
  17034. if (loadingScreen) {
  17035. loadingScreen.hideLoadingUI();
  17036. }
  17037. };
  17038. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17039. /**
  17040. * Gets the current loading screen object
  17041. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17042. */
  17043. get: function () {
  17044. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17045. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17046. return this._loadingScreen;
  17047. },
  17048. /**
  17049. * Sets the current loading screen object
  17050. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17051. */
  17052. set: function (loadingScreen) {
  17053. this._loadingScreen = loadingScreen;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17059. /**
  17060. * Sets the current loading screen text
  17061. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17062. */
  17063. set: function (text) {
  17064. this.loadingScreen.loadingUIText = text;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17070. /**
  17071. * Sets the current loading screen background color
  17072. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17073. */
  17074. set: function (color) {
  17075. this.loadingScreen.loadingUIBackgroundColor = color;
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. /**
  17081. * Attach a new callback raised when context lost event is fired
  17082. * @param callback defines the callback to call
  17083. */
  17084. Engine.prototype.attachContextLostEvent = function (callback) {
  17085. if (this._renderingCanvas) {
  17086. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17087. }
  17088. };
  17089. /**
  17090. * Attach a new callback raised when context restored event is fired
  17091. * @param callback defines the callback to call
  17092. */
  17093. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17094. if (this._renderingCanvas) {
  17095. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17096. }
  17097. };
  17098. /**
  17099. * Gets the source code of the vertex shader associated with a specific webGL program
  17100. * @param program defines the program to use
  17101. * @returns a string containing the source code of the vertex shader associated with the program
  17102. */
  17103. Engine.prototype.getVertexShaderSource = function (program) {
  17104. var shaders = this._gl.getAttachedShaders(program);
  17105. if (!shaders) {
  17106. return null;
  17107. }
  17108. return this._gl.getShaderSource(shaders[0]);
  17109. };
  17110. /**
  17111. * Gets the source code of the fragment shader associated with a specific webGL program
  17112. * @param program defines the program to use
  17113. * @returns a string containing the source code of the fragment shader associated with the program
  17114. */
  17115. Engine.prototype.getFragmentShaderSource = function (program) {
  17116. var shaders = this._gl.getAttachedShaders(program);
  17117. if (!shaders) {
  17118. return null;
  17119. }
  17120. return this._gl.getShaderSource(shaders[1]);
  17121. };
  17122. /**
  17123. * Get the current error code of the webGL context
  17124. * @returns the error code
  17125. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17126. */
  17127. Engine.prototype.getError = function () {
  17128. return this._gl.getError();
  17129. };
  17130. // FPS
  17131. /**
  17132. * Gets the current framerate
  17133. * @returns a number representing the framerate
  17134. */
  17135. Engine.prototype.getFps = function () {
  17136. return this._fps;
  17137. };
  17138. /**
  17139. * Gets the time spent between current and previous frame
  17140. * @returns a number representing the delta time in ms
  17141. */
  17142. Engine.prototype.getDeltaTime = function () {
  17143. return this._deltaTime;
  17144. };
  17145. Engine.prototype._measureFps = function () {
  17146. this._performanceMonitor.sampleFrame();
  17147. this._fps = this._performanceMonitor.averageFPS;
  17148. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17149. };
  17150. /** @hidden */
  17151. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17152. if (faceIndex === void 0) { faceIndex = -1; }
  17153. if (level === void 0) { level = 0; }
  17154. var gl = this._gl;
  17155. if (!this._dummyFramebuffer) {
  17156. var dummy = gl.createFramebuffer();
  17157. if (!dummy) {
  17158. throw new Error("Unable to create dummy framebuffer");
  17159. }
  17160. this._dummyFramebuffer = dummy;
  17161. }
  17162. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17163. if (faceIndex > -1) {
  17164. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17165. }
  17166. else {
  17167. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17168. }
  17169. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17170. var buffer;
  17171. switch (readType) {
  17172. case gl.UNSIGNED_BYTE:
  17173. buffer = new Uint8Array(4 * width * height);
  17174. readType = gl.UNSIGNED_BYTE;
  17175. break;
  17176. default:
  17177. buffer = new Float32Array(4 * width * height);
  17178. readType = gl.FLOAT;
  17179. break;
  17180. }
  17181. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17182. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17183. return buffer;
  17184. };
  17185. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17186. if (this._webGLVersion > 1) {
  17187. return this._caps.colorBufferFloat;
  17188. }
  17189. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17190. };
  17191. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17192. if (this._webGLVersion > 1) {
  17193. return this._caps.colorBufferFloat;
  17194. }
  17195. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17196. };
  17197. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17198. Engine.prototype._canRenderToFramebuffer = function (type) {
  17199. var gl = this._gl;
  17200. //clear existing errors
  17201. while (gl.getError() !== gl.NO_ERROR) { }
  17202. var successful = true;
  17203. var texture = gl.createTexture();
  17204. gl.bindTexture(gl.TEXTURE_2D, texture);
  17205. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17208. var fb = gl.createFramebuffer();
  17209. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17210. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17211. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17212. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17213. successful = successful && (gl.getError() === gl.NO_ERROR);
  17214. //try render by clearing frame buffer's color buffer
  17215. if (successful) {
  17216. gl.clear(gl.COLOR_BUFFER_BIT);
  17217. successful = successful && (gl.getError() === gl.NO_ERROR);
  17218. }
  17219. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17220. if (successful) {
  17221. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17222. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17223. var readFormat = gl.RGBA;
  17224. var readType = gl.UNSIGNED_BYTE;
  17225. var buffer = new Uint8Array(4);
  17226. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17227. successful = successful && (gl.getError() === gl.NO_ERROR);
  17228. }
  17229. //clean up
  17230. gl.deleteTexture(texture);
  17231. gl.deleteFramebuffer(fb);
  17232. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17233. //clear accumulated errors
  17234. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17235. return successful;
  17236. };
  17237. /** @hidden */
  17238. Engine.prototype._getWebGLTextureType = function (type) {
  17239. if (type === Engine.TEXTURETYPE_FLOAT) {
  17240. return this._gl.FLOAT;
  17241. }
  17242. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17243. // Add Half Float Constant.
  17244. return this._gl.HALF_FLOAT_OES;
  17245. }
  17246. return this._gl.UNSIGNED_BYTE;
  17247. };
  17248. ;
  17249. Engine.prototype._getInternalFormat = function (format) {
  17250. var internalFormat = this._gl.RGBA;
  17251. switch (format) {
  17252. case Engine.TEXTUREFORMAT_ALPHA:
  17253. internalFormat = this._gl.ALPHA;
  17254. break;
  17255. case Engine.TEXTUREFORMAT_LUMINANCE:
  17256. internalFormat = this._gl.LUMINANCE;
  17257. break;
  17258. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17259. internalFormat = this._gl.LUMINANCE_ALPHA;
  17260. break;
  17261. case Engine.TEXTUREFORMAT_RGB:
  17262. internalFormat = this._gl.RGB;
  17263. break;
  17264. case Engine.TEXTUREFORMAT_RGBA:
  17265. internalFormat = this._gl.RGBA;
  17266. break;
  17267. case Engine.TEXTUREFORMAT_R:
  17268. internalFormat = this._gl.RED;
  17269. break;
  17270. case Engine.TEXTUREFORMAT_RG:
  17271. internalFormat = this._gl.RG;
  17272. break;
  17273. }
  17274. return internalFormat;
  17275. };
  17276. /** @hidden */
  17277. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17278. if (this._webGLVersion === 1) {
  17279. if (format !== undefined) {
  17280. switch (format) {
  17281. case Engine.TEXTUREFORMAT_LUMINANCE:
  17282. return this._gl.LUMINANCE;
  17283. case Engine.TEXTUREFORMAT_ALPHA:
  17284. return this._gl.ALPHA;
  17285. }
  17286. }
  17287. return this._gl.RGBA;
  17288. }
  17289. if (type === Engine.TEXTURETYPE_FLOAT) {
  17290. if (format !== undefined) {
  17291. switch (format) {
  17292. case Engine.TEXTUREFORMAT_R:
  17293. return this._gl.R32F;
  17294. case Engine.TEXTUREFORMAT_RG:
  17295. return this._gl.RG32F;
  17296. case Engine.TEXTUREFORMAT_RGB:
  17297. return this._gl.RGB32F;
  17298. }
  17299. }
  17300. return this._gl.RGBA32F;
  17301. }
  17302. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17303. if (format) {
  17304. switch (format) {
  17305. case Engine.TEXTUREFORMAT_R:
  17306. return this._gl.R16F;
  17307. case Engine.TEXTUREFORMAT_RG:
  17308. return this._gl.RG16F;
  17309. case Engine.TEXTUREFORMAT_RGB:
  17310. return this._gl.RGB16F;
  17311. }
  17312. }
  17313. return this._gl.RGBA16F;
  17314. }
  17315. if (format !== undefined) {
  17316. switch (format) {
  17317. case Engine.TEXTUREFORMAT_LUMINANCE:
  17318. return this._gl.LUMINANCE;
  17319. case Engine.TEXTUREFORMAT_RGB:
  17320. return this._gl.RGB;
  17321. case Engine.TEXTUREFORMAT_R:
  17322. return this._gl.R8;
  17323. case Engine.TEXTUREFORMAT_RG:
  17324. return this._gl.RG8;
  17325. case Engine.TEXTUREFORMAT_ALPHA:
  17326. return this._gl.ALPHA;
  17327. }
  17328. }
  17329. return this._gl.RGBA;
  17330. };
  17331. ;
  17332. /** @hidden */
  17333. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17334. if (type === Engine.TEXTURETYPE_FLOAT) {
  17335. return this._gl.RGBA32F;
  17336. }
  17337. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17338. return this._gl.RGBA16F;
  17339. }
  17340. return this._gl.RGBA8;
  17341. };
  17342. ;
  17343. /**
  17344. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17345. * @return the new query
  17346. */
  17347. Engine.prototype.createQuery = function () {
  17348. return this._gl.createQuery();
  17349. };
  17350. /**
  17351. * Delete and release a webGL query
  17352. * @param query defines the query to delete
  17353. * @return the current engine
  17354. */
  17355. Engine.prototype.deleteQuery = function (query) {
  17356. this._gl.deleteQuery(query);
  17357. return this;
  17358. };
  17359. /**
  17360. * Check if a given query has resolved and got its value
  17361. * @param query defines the query to check
  17362. * @returns true if the query got its value
  17363. */
  17364. Engine.prototype.isQueryResultAvailable = function (query) {
  17365. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17366. };
  17367. /**
  17368. * Gets the value of a given query
  17369. * @param query defines the query to check
  17370. * @returns the value of the query
  17371. */
  17372. Engine.prototype.getQueryResult = function (query) {
  17373. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17374. };
  17375. /**
  17376. * Initiates an occlusion query
  17377. * @param algorithmType defines the algorithm to use
  17378. * @param query defines the query to use
  17379. * @returns the current engine
  17380. * @see http://doc.babylonjs.com/features/occlusionquery
  17381. */
  17382. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17383. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17384. this._gl.beginQuery(glAlgorithm, query);
  17385. return this;
  17386. };
  17387. /**
  17388. * Ends an occlusion query
  17389. * @see http://doc.babylonjs.com/features/occlusionquery
  17390. * @param algorithmType defines the algorithm to use
  17391. * @returns the current engine
  17392. */
  17393. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17394. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17395. this._gl.endQuery(glAlgorithm);
  17396. return this;
  17397. };
  17398. /* Time queries */
  17399. Engine.prototype._createTimeQuery = function () {
  17400. var timerQuery = this._caps.timerQuery;
  17401. if (timerQuery.createQueryEXT) {
  17402. return timerQuery.createQueryEXT();
  17403. }
  17404. return this.createQuery();
  17405. };
  17406. Engine.prototype._deleteTimeQuery = function (query) {
  17407. var timerQuery = this._caps.timerQuery;
  17408. if (timerQuery.deleteQueryEXT) {
  17409. timerQuery.deleteQueryEXT(query);
  17410. return;
  17411. }
  17412. this.deleteQuery(query);
  17413. };
  17414. Engine.prototype._getTimeQueryResult = function (query) {
  17415. var timerQuery = this._caps.timerQuery;
  17416. if (timerQuery.getQueryObjectEXT) {
  17417. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17418. }
  17419. return this.getQueryResult(query);
  17420. };
  17421. Engine.prototype._getTimeQueryAvailability = function (query) {
  17422. var timerQuery = this._caps.timerQuery;
  17423. if (timerQuery.getQueryObjectEXT) {
  17424. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17425. }
  17426. return this.isQueryResultAvailable(query);
  17427. };
  17428. /**
  17429. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17430. * Please note that only one query can be issued at a time
  17431. * @returns a time token used to track the time span
  17432. */
  17433. Engine.prototype.startTimeQuery = function () {
  17434. var timerQuery = this._caps.timerQuery;
  17435. if (!timerQuery) {
  17436. return null;
  17437. }
  17438. var token = new BABYLON._TimeToken();
  17439. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17440. if (this._caps.canUseTimestampForTimerQuery) {
  17441. token._startTimeQuery = this._createTimeQuery();
  17442. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17443. }
  17444. else {
  17445. if (this._currentNonTimestampToken) {
  17446. return this._currentNonTimestampToken;
  17447. }
  17448. token._timeElapsedQuery = this._createTimeQuery();
  17449. if (timerQuery.beginQueryEXT) {
  17450. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17451. }
  17452. else {
  17453. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17454. }
  17455. this._currentNonTimestampToken = token;
  17456. }
  17457. return token;
  17458. };
  17459. /**
  17460. * Ends a time query
  17461. * @param token defines the token used to measure the time span
  17462. * @returns the time spent (in ns)
  17463. */
  17464. Engine.prototype.endTimeQuery = function (token) {
  17465. var timerQuery = this._caps.timerQuery;
  17466. if (!timerQuery || !token) {
  17467. return -1;
  17468. }
  17469. if (this._caps.canUseTimestampForTimerQuery) {
  17470. if (!token._startTimeQuery) {
  17471. return -1;
  17472. }
  17473. if (!token._endTimeQuery) {
  17474. token._endTimeQuery = this._createTimeQuery();
  17475. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17476. }
  17477. }
  17478. else if (!token._timeElapsedQueryEnded) {
  17479. if (!token._timeElapsedQuery) {
  17480. return -1;
  17481. }
  17482. if (timerQuery.endQueryEXT) {
  17483. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17484. }
  17485. else {
  17486. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17487. }
  17488. token._timeElapsedQueryEnded = true;
  17489. }
  17490. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17491. var available = false;
  17492. if (token._endTimeQuery) {
  17493. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17494. }
  17495. else if (token._timeElapsedQuery) {
  17496. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17497. }
  17498. if (available && !disjoint) {
  17499. var result = 0;
  17500. if (this._caps.canUseTimestampForTimerQuery) {
  17501. if (!token._startTimeQuery || !token._endTimeQuery) {
  17502. return -1;
  17503. }
  17504. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17505. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17506. result = timeEnd - timeStart;
  17507. this._deleteTimeQuery(token._startTimeQuery);
  17508. this._deleteTimeQuery(token._endTimeQuery);
  17509. token._startTimeQuery = null;
  17510. token._endTimeQuery = null;
  17511. }
  17512. else {
  17513. if (!token._timeElapsedQuery) {
  17514. return -1;
  17515. }
  17516. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17517. this._deleteTimeQuery(token._timeElapsedQuery);
  17518. token._timeElapsedQuery = null;
  17519. token._timeElapsedQueryEnded = false;
  17520. this._currentNonTimestampToken = null;
  17521. }
  17522. return result;
  17523. }
  17524. return -1;
  17525. };
  17526. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17527. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17528. };
  17529. // Transform feedback
  17530. /**
  17531. * Creates a webGL transform feedback object
  17532. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17533. * @returns the webGL transform feedback object
  17534. */
  17535. Engine.prototype.createTransformFeedback = function () {
  17536. return this._gl.createTransformFeedback();
  17537. };
  17538. /**
  17539. * Delete a webGL transform feedback object
  17540. * @param value defines the webGL transform feedback object to delete
  17541. */
  17542. Engine.prototype.deleteTransformFeedback = function (value) {
  17543. this._gl.deleteTransformFeedback(value);
  17544. };
  17545. /**
  17546. * Bind a webGL transform feedback object to the webgl context
  17547. * @param value defines the webGL transform feedback object to bind
  17548. */
  17549. Engine.prototype.bindTransformFeedback = function (value) {
  17550. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17551. };
  17552. /**
  17553. * Begins a transform feedback operation
  17554. * @param usePoints defines if points or triangles must be used
  17555. */
  17556. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17557. if (usePoints === void 0) { usePoints = true; }
  17558. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17559. };
  17560. /**
  17561. * Ends a transform feedback operation
  17562. */
  17563. Engine.prototype.endTransformFeedback = function () {
  17564. this._gl.endTransformFeedback();
  17565. };
  17566. /**
  17567. * Specify the varyings to use with transform feedback
  17568. * @param program defines the associated webGL program
  17569. * @param value defines the list of strings representing the varying names
  17570. */
  17571. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17572. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17573. };
  17574. /**
  17575. * Bind a webGL buffer for a transform feedback operation
  17576. * @param value defines the webGL buffer to bind
  17577. */
  17578. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17579. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17580. };
  17581. /** @hidden */
  17582. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17583. var _this = this;
  17584. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17585. this._activeRequests.push(request);
  17586. request.onCompleteObservable.add(function (request) {
  17587. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17588. });
  17589. return request;
  17590. };
  17591. /** @hidden */
  17592. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17593. var _this = this;
  17594. return new Promise(function (resolve, reject) {
  17595. _this._loadFile(url, function (data) {
  17596. resolve(data);
  17597. }, undefined, database, useArrayBuffer, function (request, exception) {
  17598. reject(exception);
  17599. });
  17600. });
  17601. };
  17602. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17603. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17604. var onload = function (data) {
  17605. loadedFiles[index] = data;
  17606. loadedFiles._internalCount++;
  17607. if (loadedFiles._internalCount === 6) {
  17608. onfinish(loadedFiles);
  17609. }
  17610. };
  17611. var onerror = function (request, exception) {
  17612. if (onErrorCallBack && request) {
  17613. onErrorCallBack(request.status + " " + request.statusText, exception);
  17614. }
  17615. };
  17616. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17617. };
  17618. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17619. if (onError === void 0) { onError = null; }
  17620. var loadedFiles = [];
  17621. loadedFiles._internalCount = 0;
  17622. for (var index = 0; index < 6; index++) {
  17623. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17624. }
  17625. };
  17626. // Statics
  17627. /**
  17628. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17629. * @returns true if the engine can be created
  17630. * @ignorenaming
  17631. */
  17632. Engine.isSupported = function () {
  17633. try {
  17634. var tempcanvas = document.createElement("canvas");
  17635. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17636. return gl != null && !!window.WebGLRenderingContext;
  17637. }
  17638. catch (e) {
  17639. return false;
  17640. }
  17641. };
  17642. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17643. Engine.ExceptionList = [
  17644. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17645. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17646. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17647. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17648. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17649. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17650. ];
  17651. /** Gets the list of created engines */
  17652. Engine.Instances = new Array();
  17653. // Const statics
  17654. Engine._ALPHA_DISABLE = 0;
  17655. Engine._ALPHA_ADD = 1;
  17656. Engine._ALPHA_COMBINE = 2;
  17657. Engine._ALPHA_SUBTRACT = 3;
  17658. Engine._ALPHA_MULTIPLY = 4;
  17659. Engine._ALPHA_MAXIMIZED = 5;
  17660. Engine._ALPHA_ONEONE = 6;
  17661. Engine._ALPHA_PREMULTIPLIED = 7;
  17662. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17663. Engine._ALPHA_INTERPOLATE = 9;
  17664. Engine._ALPHA_SCREENMODE = 10;
  17665. Engine._DELAYLOADSTATE_NONE = 0;
  17666. Engine._DELAYLOADSTATE_LOADED = 1;
  17667. Engine._DELAYLOADSTATE_LOADING = 2;
  17668. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17669. Engine._TEXTUREFORMAT_ALPHA = 0;
  17670. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17671. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17672. Engine._TEXTUREFORMAT_RGB = 4;
  17673. Engine._TEXTUREFORMAT_RGBA = 5;
  17674. Engine._TEXTUREFORMAT_R = 6;
  17675. Engine._TEXTUREFORMAT_RG = 7;
  17676. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17677. Engine._TEXTURETYPE_FLOAT = 1;
  17678. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17679. // Depht or Stencil test Constants.
  17680. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17681. Engine._ALWAYS = 0x0207; // 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.
  17682. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17683. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17684. Engine._LEQUAL = 0x0203; // 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.
  17685. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17686. Engine._GEQUAL = 0x0206; // 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.
  17687. Engine._NOTEQUAL = 0x0205; // 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.
  17688. // Stencil Actions Constants.
  17689. Engine._KEEP = 0x1E00;
  17690. Engine._REPLACE = 0x1E01;
  17691. Engine._INCR = 0x1E02;
  17692. Engine._DECR = 0x1E03;
  17693. Engine._INVERT = 0x150A;
  17694. Engine._INCR_WRAP = 0x8507;
  17695. Engine._DECR_WRAP = 0x8508;
  17696. // Texture rescaling mode
  17697. Engine._SCALEMODE_FLOOR = 1;
  17698. Engine._SCALEMODE_NEAREST = 2;
  17699. Engine._SCALEMODE_CEILING = 3;
  17700. // Updatable statics so stick with vars here
  17701. /**
  17702. * Gets or sets the epsilon value used by collision engine
  17703. */
  17704. Engine.CollisionsEpsilon = 0.001;
  17705. /**
  17706. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17707. */
  17708. Engine.CodeRepository = "src/";
  17709. /**
  17710. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17711. */
  17712. Engine.ShadersRepository = "src/Shaders/";
  17713. return Engine;
  17714. }());
  17715. BABYLON.Engine = Engine;
  17716. })(BABYLON || (BABYLON = {}));
  17717. //# sourceMappingURL=babylon.engine.js.map
  17718. var BABYLON;
  17719. (function (BABYLON) {
  17720. /**
  17721. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17722. */
  17723. var Node = /** @class */ (function () {
  17724. /**
  17725. * Creates a new Node
  17726. * @param {string} name - the name and id to be given to this node
  17727. * @param {BABYLON.Scene} the scene this node will be added to
  17728. */
  17729. function Node(name, scene) {
  17730. if (scene === void 0) { scene = null; }
  17731. /**
  17732. * Gets or sets a string used to store user defined state for the node
  17733. */
  17734. this.state = "";
  17735. /**
  17736. * Gets or sets an object used to store user defined information for the node
  17737. */
  17738. this.metadata = null;
  17739. /**
  17740. * Gets or sets a boolean used to define if the node must be serialized
  17741. */
  17742. this.doNotSerialize = false;
  17743. /** @hidden */
  17744. this._isDisposed = false;
  17745. /**
  17746. * Gets a list of Animations associated with the node
  17747. */
  17748. this.animations = new Array();
  17749. this._ranges = {};
  17750. this._isEnabled = true;
  17751. this._isReady = true;
  17752. /** @hidden */
  17753. this._currentRenderId = -1;
  17754. this._parentRenderId = -1;
  17755. this._childRenderId = -1;
  17756. this._animationPropertiesOverride = null;
  17757. /**
  17758. * An event triggered when the mesh is disposed
  17759. */
  17760. this.onDisposeObservable = new BABYLON.Observable();
  17761. // Behaviors
  17762. this._behaviors = new Array();
  17763. this.name = name;
  17764. this.id = name;
  17765. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17766. this.uniqueId = this._scene.getUniqueId();
  17767. this._initCache();
  17768. }
  17769. /**
  17770. * Gets a boolean indicating if the node has been disposed
  17771. * @returns true if the node was disposed
  17772. */
  17773. Node.prototype.isDisposed = function () {
  17774. return this._isDisposed;
  17775. };
  17776. Object.defineProperty(Node.prototype, "parent", {
  17777. get: function () {
  17778. return this._parentNode;
  17779. },
  17780. /**
  17781. * Gets or sets the parent of the node
  17782. */
  17783. set: function (parent) {
  17784. if (this._parentNode === parent) {
  17785. return;
  17786. }
  17787. // Remove self from list of children of parent
  17788. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17789. var index = this._parentNode._children.indexOf(this);
  17790. if (index !== -1) {
  17791. this._parentNode._children.splice(index, 1);
  17792. }
  17793. }
  17794. // Store new parent
  17795. this._parentNode = parent;
  17796. // Add as child to new parent
  17797. if (this._parentNode) {
  17798. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17799. this._parentNode._children = new Array();
  17800. }
  17801. this._parentNode._children.push(this);
  17802. }
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17808. /**
  17809. * Gets or sets the animation properties override
  17810. */
  17811. get: function () {
  17812. if (!this._animationPropertiesOverride) {
  17813. return this._scene.animationPropertiesOverride;
  17814. }
  17815. return this._animationPropertiesOverride;
  17816. },
  17817. set: function (value) {
  17818. this._animationPropertiesOverride = value;
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. /**
  17824. * Gets a string idenfifying the name of the class
  17825. * @returns "Node" string
  17826. */
  17827. Node.prototype.getClassName = function () {
  17828. return "Node";
  17829. };
  17830. Object.defineProperty(Node.prototype, "onDispose", {
  17831. /**
  17832. * Sets a callback that will be raised when the node will be disposed
  17833. */
  17834. set: function (callback) {
  17835. if (this._onDisposeObserver) {
  17836. this.onDisposeObservable.remove(this._onDisposeObserver);
  17837. }
  17838. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. /**
  17844. * Gets the scene of the node
  17845. * @returns a {BABYLON.Scene}
  17846. */
  17847. Node.prototype.getScene = function () {
  17848. return this._scene;
  17849. };
  17850. /**
  17851. * Gets the engine of the node
  17852. * @returns a {BABYLON.Engine}
  17853. */
  17854. Node.prototype.getEngine = function () {
  17855. return this._scene.getEngine();
  17856. };
  17857. /**
  17858. * Attach a behavior to the node
  17859. * @see http://doc.babylonjs.com/features/behaviour
  17860. * @param behavior defines the behavior to attach
  17861. * @returns the current Node
  17862. */
  17863. Node.prototype.addBehavior = function (behavior) {
  17864. var _this = this;
  17865. var index = this._behaviors.indexOf(behavior);
  17866. if (index !== -1) {
  17867. return this;
  17868. }
  17869. behavior.init();
  17870. if (this._scene.isLoading) {
  17871. // We defer the attach when the scene will be loaded
  17872. this._scene.onDataLoadedObservable.addOnce(function () {
  17873. behavior.attach(_this);
  17874. });
  17875. }
  17876. else {
  17877. behavior.attach(this);
  17878. }
  17879. this._behaviors.push(behavior);
  17880. return this;
  17881. };
  17882. /**
  17883. * Remove an attached behavior
  17884. * @see http://doc.babylonjs.com/features/behaviour
  17885. * @param behavior defines the behavior to attach
  17886. * @returns the current Node
  17887. */
  17888. Node.prototype.removeBehavior = function (behavior) {
  17889. var index = this._behaviors.indexOf(behavior);
  17890. if (index === -1) {
  17891. return this;
  17892. }
  17893. this._behaviors[index].detach();
  17894. this._behaviors.splice(index, 1);
  17895. return this;
  17896. };
  17897. Object.defineProperty(Node.prototype, "behaviors", {
  17898. /**
  17899. * Gets the list of attached behaviors
  17900. * @see http://doc.babylonjs.com/features/behaviour
  17901. */
  17902. get: function () {
  17903. return this._behaviors;
  17904. },
  17905. enumerable: true,
  17906. configurable: true
  17907. });
  17908. /**
  17909. * Gets an attached behavior by name
  17910. * @param name defines the name of the behavior to look for
  17911. * @see http://doc.babylonjs.com/features/behaviour
  17912. * @returns null if behavior was not found else the requested behavior
  17913. */
  17914. Node.prototype.getBehaviorByName = function (name) {
  17915. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17916. var behavior = _a[_i];
  17917. if (behavior.name === name) {
  17918. return behavior;
  17919. }
  17920. }
  17921. return null;
  17922. };
  17923. /**
  17924. * Returns the world matrix of the node
  17925. * @returns a matrix containing the node's world matrix
  17926. */
  17927. Node.prototype.getWorldMatrix = function () {
  17928. return BABYLON.Matrix.Identity();
  17929. };
  17930. /** @hidden */
  17931. Node.prototype._getWorldMatrixDeterminant = function () {
  17932. return 1;
  17933. };
  17934. // override it in derived class if you add new variables to the cache
  17935. // and call the parent class method
  17936. /** @hidden */
  17937. Node.prototype._initCache = function () {
  17938. this._cache = {};
  17939. this._cache.parent = undefined;
  17940. };
  17941. /** @hidden */
  17942. Node.prototype.updateCache = function (force) {
  17943. if (!force && this.isSynchronized())
  17944. return;
  17945. this._cache.parent = this.parent;
  17946. this._updateCache();
  17947. };
  17948. // override it in derived class if you add new variables to the cache
  17949. // and call the parent class method if !ignoreParentClass
  17950. /** @hidden */
  17951. Node.prototype._updateCache = function (ignoreParentClass) {
  17952. };
  17953. // override it in derived class if you add new variables to the cache
  17954. /** @hidden */
  17955. Node.prototype._isSynchronized = function () {
  17956. return true;
  17957. };
  17958. /** @hidden */
  17959. Node.prototype._markSyncedWithParent = function () {
  17960. if (this.parent) {
  17961. this._parentRenderId = this.parent._childRenderId;
  17962. }
  17963. };
  17964. /** @hidden */
  17965. Node.prototype.isSynchronizedWithParent = function () {
  17966. if (!this.parent) {
  17967. return true;
  17968. }
  17969. if (this._parentRenderId !== this.parent._childRenderId) {
  17970. return false;
  17971. }
  17972. return this.parent.isSynchronized();
  17973. };
  17974. /** @hidden */
  17975. Node.prototype.isSynchronized = function (updateCache) {
  17976. var check = this.hasNewParent();
  17977. check = check || !this.isSynchronizedWithParent();
  17978. check = check || !this._isSynchronized();
  17979. if (updateCache)
  17980. this.updateCache(true);
  17981. return !check;
  17982. };
  17983. /** @hidden */
  17984. Node.prototype.hasNewParent = function (update) {
  17985. if (this._cache.parent === this.parent)
  17986. return false;
  17987. if (update)
  17988. this._cache.parent = this.parent;
  17989. return true;
  17990. };
  17991. /**
  17992. * Is this node ready to be used/rendered
  17993. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17994. * @return true if the node is ready
  17995. */
  17996. Node.prototype.isReady = function (completeCheck) {
  17997. if (completeCheck === void 0) { completeCheck = false; }
  17998. return this._isReady;
  17999. };
  18000. /**
  18001. * Is this node enabled?
  18002. * 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
  18003. * @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
  18004. * @return whether this node (and its parent) is enabled
  18005. */
  18006. Node.prototype.isEnabled = function (checkAncestors) {
  18007. if (checkAncestors === void 0) { checkAncestors = true; }
  18008. if (checkAncestors === false) {
  18009. return this._isEnabled;
  18010. }
  18011. if (this._isEnabled === false) {
  18012. return false;
  18013. }
  18014. if (this.parent !== undefined && this.parent !== null) {
  18015. return this.parent.isEnabled(checkAncestors);
  18016. }
  18017. return true;
  18018. };
  18019. /**
  18020. * Set the enabled state of this node
  18021. * @param value defines the new enabled state
  18022. */
  18023. Node.prototype.setEnabled = function (value) {
  18024. this._isEnabled = value;
  18025. };
  18026. /**
  18027. * Is this node a descendant of the given node?
  18028. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18029. * @param ancestor defines the parent node to inspect
  18030. * @returns a boolean indicating if this node is a descendant of the given node
  18031. */
  18032. Node.prototype.isDescendantOf = function (ancestor) {
  18033. if (this.parent) {
  18034. if (this.parent === ancestor) {
  18035. return true;
  18036. }
  18037. return this.parent.isDescendantOf(ancestor);
  18038. }
  18039. return false;
  18040. };
  18041. /** @hidden */
  18042. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18043. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18044. if (!this._children) {
  18045. return;
  18046. }
  18047. for (var index = 0; index < this._children.length; index++) {
  18048. var item = this._children[index];
  18049. if (!predicate || predicate(item)) {
  18050. results.push(item);
  18051. }
  18052. if (!directDescendantsOnly) {
  18053. item._getDescendants(results, false, predicate);
  18054. }
  18055. }
  18056. };
  18057. /**
  18058. * Will return all nodes that have this node as ascendant
  18059. * @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
  18060. * @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
  18061. * @return all children nodes of all types
  18062. */
  18063. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18064. var results = new Array();
  18065. this._getDescendants(results, directDescendantsOnly, predicate);
  18066. return results;
  18067. };
  18068. /**
  18069. * Get all child-meshes of this node
  18070. * @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
  18071. * @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
  18072. * @returns an array of {BABYLON.AbstractMesh}
  18073. */
  18074. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18075. var results = [];
  18076. this._getDescendants(results, directDescendantsOnly, function (node) {
  18077. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18078. });
  18079. return results;
  18080. };
  18081. /**
  18082. * Get all child-transformNodes of this node
  18083. * @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
  18084. * @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
  18085. * @returns an array of {BABYLON.TransformNode}
  18086. */
  18087. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18088. var results = [];
  18089. this._getDescendants(results, directDescendantsOnly, function (node) {
  18090. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18091. });
  18092. return results;
  18093. };
  18094. /**
  18095. * Get all direct children of this node
  18096. * @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
  18097. * @returns an array of {BABYLON.Node}
  18098. */
  18099. Node.prototype.getChildren = function (predicate) {
  18100. return this.getDescendants(true, predicate);
  18101. };
  18102. /** @hidden */
  18103. Node.prototype._setReady = function (state) {
  18104. if (state === this._isReady) {
  18105. return;
  18106. }
  18107. if (!state) {
  18108. this._isReady = false;
  18109. return;
  18110. }
  18111. if (this.onReady) {
  18112. this.onReady(this);
  18113. }
  18114. this._isReady = true;
  18115. };
  18116. /**
  18117. * Get an animation by name
  18118. * @param name defines the name of the animation to look for
  18119. * @returns null if not found else the requested animation
  18120. */
  18121. Node.prototype.getAnimationByName = function (name) {
  18122. for (var i = 0; i < this.animations.length; i++) {
  18123. var animation = this.animations[i];
  18124. if (animation.name === name) {
  18125. return animation;
  18126. }
  18127. }
  18128. return null;
  18129. };
  18130. /**
  18131. * Creates an animation range for this node
  18132. * @param name defines the name of the range
  18133. * @param from defines the starting key
  18134. * @param to defines the end key
  18135. */
  18136. Node.prototype.createAnimationRange = function (name, from, to) {
  18137. // check name not already in use
  18138. if (!this._ranges[name]) {
  18139. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18140. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18141. if (this.animations[i]) {
  18142. this.animations[i].createRange(name, from, to);
  18143. }
  18144. }
  18145. }
  18146. };
  18147. /**
  18148. * Delete a specific animation range
  18149. * @param name defines the name of the range to delete
  18150. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18151. */
  18152. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18153. if (deleteFrames === void 0) { deleteFrames = true; }
  18154. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18155. if (this.animations[i]) {
  18156. this.animations[i].deleteRange(name, deleteFrames);
  18157. }
  18158. }
  18159. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18160. };
  18161. /**
  18162. * Get an animation range by name
  18163. * @param name defines the name of the animation range to look for
  18164. * @returns null if not found else the requested animation range
  18165. */
  18166. Node.prototype.getAnimationRange = function (name) {
  18167. return this._ranges[name];
  18168. };
  18169. /**
  18170. * Will start the animation sequence
  18171. * @param name defines the range frames for animation sequence
  18172. * @param loop defines if the animation should loop (false by default)
  18173. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18174. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18175. * @returns the object created for this animation. If range does not exist, it will return null
  18176. */
  18177. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18178. var range = this.getAnimationRange(name);
  18179. if (!range) {
  18180. return null;
  18181. }
  18182. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18183. };
  18184. /**
  18185. * Serialize animation ranges into a JSON compatible object
  18186. * @returns serialization object
  18187. */
  18188. Node.prototype.serializeAnimationRanges = function () {
  18189. var serializationRanges = [];
  18190. for (var name in this._ranges) {
  18191. var localRange = this._ranges[name];
  18192. if (!localRange) {
  18193. continue;
  18194. }
  18195. var range = {};
  18196. range.name = name;
  18197. range.from = localRange.from;
  18198. range.to = localRange.to;
  18199. serializationRanges.push(range);
  18200. }
  18201. return serializationRanges;
  18202. };
  18203. /**
  18204. * Computes the world matrix of the node
  18205. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18206. * @returns the world matrix
  18207. */
  18208. Node.prototype.computeWorldMatrix = function (force) {
  18209. return BABYLON.Matrix.Identity();
  18210. };
  18211. /**
  18212. * Releases resources associated with this node.
  18213. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18214. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18215. */
  18216. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18217. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18218. if (!doNotRecurse) {
  18219. var nodes = this.getDescendants(true);
  18220. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18221. var node = nodes_1[_i];
  18222. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18223. }
  18224. }
  18225. else {
  18226. var transformNodes = this.getChildTransformNodes(true);
  18227. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18228. var transformNode = transformNodes_1[_a];
  18229. transformNode.parent = null;
  18230. transformNode.computeWorldMatrix(true);
  18231. }
  18232. }
  18233. this.parent = null;
  18234. // Callback
  18235. this.onDisposeObservable.notifyObservers(this);
  18236. this.onDisposeObservable.clear();
  18237. // Behaviors
  18238. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18239. var behavior = _c[_b];
  18240. behavior.detach();
  18241. }
  18242. this._behaviors = [];
  18243. this._isDisposed = true;
  18244. };
  18245. /**
  18246. * Parse animation range data from a serialization object and store them into a given node
  18247. * @param node defines where to store the animation ranges
  18248. * @param parsedNode defines the serialization object to read data from
  18249. * @param scene defines the hosting scene
  18250. */
  18251. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18252. if (parsedNode.ranges) {
  18253. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18254. var data = parsedNode.ranges[index];
  18255. node.createAnimationRange(data.name, data.from, data.to);
  18256. }
  18257. }
  18258. };
  18259. __decorate([
  18260. BABYLON.serialize()
  18261. ], Node.prototype, "name", void 0);
  18262. __decorate([
  18263. BABYLON.serialize()
  18264. ], Node.prototype, "id", void 0);
  18265. __decorate([
  18266. BABYLON.serialize()
  18267. ], Node.prototype, "uniqueId", void 0);
  18268. __decorate([
  18269. BABYLON.serialize()
  18270. ], Node.prototype, "state", void 0);
  18271. __decorate([
  18272. BABYLON.serialize()
  18273. ], Node.prototype, "metadata", void 0);
  18274. return Node;
  18275. }());
  18276. BABYLON.Node = Node;
  18277. })(BABYLON || (BABYLON = {}));
  18278. //# sourceMappingURL=babylon.node.js.map
  18279. var BABYLON;
  18280. (function (BABYLON) {
  18281. var BoundingSphere = /** @class */ (function () {
  18282. /**
  18283. * Creates a new bounding sphere
  18284. * @param min defines the minimum vector (in local space)
  18285. * @param max defines the maximum vector (in local space)
  18286. */
  18287. function BoundingSphere(min, max) {
  18288. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18289. this.reConstruct(min, max);
  18290. }
  18291. /**
  18292. * Recreates the entire bounding sphere from scratch
  18293. * @param min defines the new minimum vector (in local space)
  18294. * @param max defines the new maximum vector (in local space)
  18295. */
  18296. BoundingSphere.prototype.reConstruct = function (min, max) {
  18297. this.minimum = min.clone();
  18298. this.maximum = max.clone();
  18299. var distance = BABYLON.Vector3.Distance(min, max);
  18300. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18301. this.radius = distance * 0.5;
  18302. this.centerWorld = BABYLON.Vector3.Zero();
  18303. this._update(BABYLON.Matrix.Identity());
  18304. };
  18305. // Methods
  18306. BoundingSphere.prototype._update = function (world) {
  18307. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18308. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18309. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18310. };
  18311. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18312. for (var i = 0; i < 6; i++) {
  18313. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18314. return false;
  18315. }
  18316. return true;
  18317. };
  18318. BoundingSphere.prototype.intersectsPoint = function (point) {
  18319. var x = this.centerWorld.x - point.x;
  18320. var y = this.centerWorld.y - point.y;
  18321. var z = this.centerWorld.z - point.z;
  18322. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18323. if (this.radiusWorld < distance)
  18324. return false;
  18325. return true;
  18326. };
  18327. // Statics
  18328. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18329. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18330. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18331. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18332. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18333. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18334. return false;
  18335. return true;
  18336. };
  18337. return BoundingSphere;
  18338. }());
  18339. BABYLON.BoundingSphere = BoundingSphere;
  18340. })(BABYLON || (BABYLON = {}));
  18341. //# sourceMappingURL=babylon.boundingSphere.js.map
  18342. var BABYLON;
  18343. (function (BABYLON) {
  18344. var BoundingBox = /** @class */ (function () {
  18345. /**
  18346. * Creates a new bounding box
  18347. * @param min defines the minimum vector (in local space)
  18348. * @param max defines the maximum vector (in local space)
  18349. */
  18350. function BoundingBox(min, max) {
  18351. this.vectorsWorld = new Array();
  18352. this.reConstruct(min, max);
  18353. }
  18354. // Methods
  18355. /**
  18356. * Recreates the entire bounding box from scratch
  18357. * @param min defines the new minimum vector (in local space)
  18358. * @param max defines the new maximum vector (in local space)
  18359. */
  18360. BoundingBox.prototype.reConstruct = function (min, max) {
  18361. this.minimum = min.clone();
  18362. this.maximum = max.clone();
  18363. // Bounding vectors
  18364. this.vectors = new Array();
  18365. this.vectors.push(this.minimum.clone());
  18366. this.vectors.push(this.maximum.clone());
  18367. this.vectors.push(this.minimum.clone());
  18368. this.vectors[2].x = this.maximum.x;
  18369. this.vectors.push(this.minimum.clone());
  18370. this.vectors[3].y = this.maximum.y;
  18371. this.vectors.push(this.minimum.clone());
  18372. this.vectors[4].z = this.maximum.z;
  18373. this.vectors.push(this.maximum.clone());
  18374. this.vectors[5].z = this.minimum.z;
  18375. this.vectors.push(this.maximum.clone());
  18376. this.vectors[6].x = this.minimum.x;
  18377. this.vectors.push(this.maximum.clone());
  18378. this.vectors[7].y = this.minimum.y;
  18379. // OBB
  18380. this.center = this.maximum.add(this.minimum).scale(0.5);
  18381. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18382. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18383. // World
  18384. for (var index = 0; index < this.vectors.length; index++) {
  18385. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18386. }
  18387. this.minimumWorld = BABYLON.Vector3.Zero();
  18388. this.maximumWorld = BABYLON.Vector3.Zero();
  18389. this.centerWorld = BABYLON.Vector3.Zero();
  18390. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18391. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18392. };
  18393. BoundingBox.prototype.getWorldMatrix = function () {
  18394. return this._worldMatrix;
  18395. };
  18396. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18397. this._worldMatrix.copyFrom(matrix);
  18398. return this;
  18399. };
  18400. BoundingBox.prototype._update = function (world) {
  18401. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18402. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18403. for (var index = 0; index < this.vectors.length; index++) {
  18404. var v = this.vectorsWorld[index];
  18405. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18406. if (v.x < this.minimumWorld.x)
  18407. this.minimumWorld.x = v.x;
  18408. if (v.y < this.minimumWorld.y)
  18409. this.minimumWorld.y = v.y;
  18410. if (v.z < this.minimumWorld.z)
  18411. this.minimumWorld.z = v.z;
  18412. if (v.x > this.maximumWorld.x)
  18413. this.maximumWorld.x = v.x;
  18414. if (v.y > this.maximumWorld.y)
  18415. this.maximumWorld.y = v.y;
  18416. if (v.z > this.maximumWorld.z)
  18417. this.maximumWorld.z = v.z;
  18418. }
  18419. // Extend
  18420. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18421. this.extendSizeWorld.scaleInPlace(0.5);
  18422. // OBB
  18423. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18424. this.centerWorld.scaleInPlace(0.5);
  18425. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18426. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18427. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18428. this._worldMatrix = world;
  18429. };
  18430. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18431. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18432. };
  18433. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18434. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18435. };
  18436. BoundingBox.prototype.intersectsPoint = function (point) {
  18437. var delta = -BABYLON.Epsilon;
  18438. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18439. return false;
  18440. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18441. return false;
  18442. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18443. return false;
  18444. return true;
  18445. };
  18446. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18447. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18448. };
  18449. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18450. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18451. return false;
  18452. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18453. return false;
  18454. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18455. return false;
  18456. return true;
  18457. };
  18458. // Statics
  18459. BoundingBox.Intersects = function (box0, box1) {
  18460. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18461. return false;
  18462. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18463. return false;
  18464. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18465. return false;
  18466. return true;
  18467. };
  18468. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18469. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18470. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18471. return (num <= (sphereRadius * sphereRadius));
  18472. };
  18473. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18474. for (var p = 0; p < 6; p++) {
  18475. for (var i = 0; i < 8; i++) {
  18476. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18477. return false;
  18478. }
  18479. }
  18480. }
  18481. return true;
  18482. };
  18483. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18484. for (var p = 0; p < 6; p++) {
  18485. var inCount = 8;
  18486. for (var i = 0; i < 8; i++) {
  18487. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18488. --inCount;
  18489. }
  18490. else {
  18491. break;
  18492. }
  18493. }
  18494. if (inCount === 0)
  18495. return false;
  18496. }
  18497. return true;
  18498. };
  18499. return BoundingBox;
  18500. }());
  18501. BABYLON.BoundingBox = BoundingBox;
  18502. })(BABYLON || (BABYLON = {}));
  18503. //# sourceMappingURL=babylon.boundingBox.js.map
  18504. var BABYLON;
  18505. (function (BABYLON) {
  18506. var computeBoxExtents = function (axis, box) {
  18507. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18508. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18509. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18510. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18511. var r = r0 + r1 + r2;
  18512. return {
  18513. min: p - r,
  18514. max: p + r
  18515. };
  18516. };
  18517. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18518. var axisOverlap = function (axis, box0, box1) {
  18519. var result0 = computeBoxExtents(axis, box0);
  18520. var result1 = computeBoxExtents(axis, box1);
  18521. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18522. };
  18523. var BoundingInfo = /** @class */ (function () {
  18524. function BoundingInfo(minimum, maximum) {
  18525. this.minimum = minimum;
  18526. this.maximum = maximum;
  18527. this._isLocked = false;
  18528. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18529. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18530. }
  18531. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18532. get: function () {
  18533. return this._isLocked;
  18534. },
  18535. set: function (value) {
  18536. this._isLocked = value;
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. // Methods
  18542. BoundingInfo.prototype.update = function (world) {
  18543. if (this._isLocked) {
  18544. return;
  18545. }
  18546. this.boundingBox._update(world);
  18547. this.boundingSphere._update(world);
  18548. };
  18549. /**
  18550. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18551. * @param center New center of the bounding info
  18552. * @param extend New extend of the bounding info
  18553. */
  18554. BoundingInfo.prototype.centerOn = function (center, extend) {
  18555. this.minimum = center.subtract(extend);
  18556. this.maximum = center.add(extend);
  18557. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18558. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18559. return this;
  18560. };
  18561. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18562. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18563. return false;
  18564. return this.boundingBox.isInFrustum(frustumPlanes);
  18565. };
  18566. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18567. /**
  18568. * Gets the world distance between the min and max points of the bounding box
  18569. */
  18570. get: function () {
  18571. var boundingBox = this.boundingBox;
  18572. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18573. return size.length();
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18579. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18580. };
  18581. BoundingInfo.prototype._checkCollision = function (collider) {
  18582. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18583. };
  18584. BoundingInfo.prototype.intersectsPoint = function (point) {
  18585. if (!this.boundingSphere.centerWorld) {
  18586. return false;
  18587. }
  18588. if (!this.boundingSphere.intersectsPoint(point)) {
  18589. return false;
  18590. }
  18591. if (!this.boundingBox.intersectsPoint(point)) {
  18592. return false;
  18593. }
  18594. return true;
  18595. };
  18596. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18597. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18598. return false;
  18599. }
  18600. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18601. return false;
  18602. }
  18603. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18604. return false;
  18605. }
  18606. if (!precise) {
  18607. return true;
  18608. }
  18609. var box0 = this.boundingBox;
  18610. var box1 = boundingInfo.boundingBox;
  18611. if (!axisOverlap(box0.directions[0], box0, box1))
  18612. return false;
  18613. if (!axisOverlap(box0.directions[1], box0, box1))
  18614. return false;
  18615. if (!axisOverlap(box0.directions[2], box0, box1))
  18616. return false;
  18617. if (!axisOverlap(box1.directions[0], box0, box1))
  18618. return false;
  18619. if (!axisOverlap(box1.directions[1], box0, box1))
  18620. return false;
  18621. if (!axisOverlap(box1.directions[2], box0, box1))
  18622. return false;
  18623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18624. return false;
  18625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18626. return false;
  18627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18628. return false;
  18629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18630. return false;
  18631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18632. return false;
  18633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18634. return false;
  18635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18636. return false;
  18637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18638. return false;
  18639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18640. return false;
  18641. return true;
  18642. };
  18643. return BoundingInfo;
  18644. }());
  18645. BABYLON.BoundingInfo = BoundingInfo;
  18646. })(BABYLON || (BABYLON = {}));
  18647. //# sourceMappingURL=babylon.boundingInfo.js.map
  18648. var BABYLON;
  18649. (function (BABYLON) {
  18650. var TransformNode = /** @class */ (function (_super) {
  18651. __extends(TransformNode, _super);
  18652. function TransformNode(name, scene, isPure) {
  18653. if (scene === void 0) { scene = null; }
  18654. if (isPure === void 0) { isPure = true; }
  18655. var _this = _super.call(this, name, scene) || this;
  18656. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18657. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18658. _this._up = new BABYLON.Vector3(0, 1, 0);
  18659. _this._right = new BABYLON.Vector3(1, 0, 0);
  18660. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18661. // Properties
  18662. _this._rotation = BABYLON.Vector3.Zero();
  18663. _this._scaling = BABYLON.Vector3.One();
  18664. _this._isDirty = false;
  18665. /**
  18666. * Set the billboard mode. Default is 0.
  18667. *
  18668. * | Value | Type | Description |
  18669. * | --- | --- | --- |
  18670. * | 0 | BILLBOARDMODE_NONE | |
  18671. * | 1 | BILLBOARDMODE_X | |
  18672. * | 2 | BILLBOARDMODE_Y | |
  18673. * | 4 | BILLBOARDMODE_Z | |
  18674. * | 7 | BILLBOARDMODE_ALL | |
  18675. *
  18676. */
  18677. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18678. _this.scalingDeterminant = 1;
  18679. _this.infiniteDistance = false;
  18680. /**
  18681. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18682. * By default the system will update normals to compensate
  18683. */
  18684. _this.ignoreNonUniformScaling = false;
  18685. _this.position = BABYLON.Vector3.Zero();
  18686. _this._localWorld = BABYLON.Matrix.Zero();
  18687. _this._worldMatrix = BABYLON.Matrix.Zero();
  18688. _this._worldMatrixDeterminant = 0;
  18689. _this._absolutePosition = BABYLON.Vector3.Zero();
  18690. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18691. _this._postMultiplyPivotMatrix = false;
  18692. _this._isWorldMatrixFrozen = false;
  18693. /**
  18694. * An event triggered after the world matrix is updated
  18695. */
  18696. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18697. _this._nonUniformScaling = false;
  18698. if (isPure) {
  18699. _this.getScene().addTransformNode(_this);
  18700. }
  18701. return _this;
  18702. }
  18703. /**
  18704. * Gets a string idenfifying the name of the class
  18705. * @returns "TransformNode" string
  18706. */
  18707. TransformNode.prototype.getClassName = function () {
  18708. return "TransformNode";
  18709. };
  18710. Object.defineProperty(TransformNode.prototype, "rotation", {
  18711. /**
  18712. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18713. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18714. * Default : (0.0, 0.0, 0.0)
  18715. */
  18716. get: function () {
  18717. return this._rotation;
  18718. },
  18719. set: function (newRotation) {
  18720. this._rotation = newRotation;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Object.defineProperty(TransformNode.prototype, "scaling", {
  18726. /**
  18727. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18728. * Default : (1.0, 1.0, 1.0)
  18729. */
  18730. get: function () {
  18731. return this._scaling;
  18732. },
  18733. /**
  18734. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18735. * Default : (1.0, 1.0, 1.0)
  18736. */
  18737. set: function (newScaling) {
  18738. this._scaling = newScaling;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18744. /**
  18745. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18746. * It's null by default.
  18747. * 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)
  18748. */
  18749. get: function () {
  18750. return this._rotationQuaternion;
  18751. },
  18752. set: function (quaternion) {
  18753. this._rotationQuaternion = quaternion;
  18754. //reset the rotation vector.
  18755. if (quaternion && this.rotation.length()) {
  18756. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18757. }
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Object.defineProperty(TransformNode.prototype, "forward", {
  18763. /**
  18764. * The forward direction of that transform in world space.
  18765. */
  18766. get: function () {
  18767. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(TransformNode.prototype, "up", {
  18773. /**
  18774. * The up direction of that transform in world space.
  18775. */
  18776. get: function () {
  18777. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18778. },
  18779. enumerable: true,
  18780. configurable: true
  18781. });
  18782. Object.defineProperty(TransformNode.prototype, "right", {
  18783. /**
  18784. * The right direction of that transform in world space.
  18785. */
  18786. get: function () {
  18787. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18788. },
  18789. enumerable: true,
  18790. configurable: true
  18791. });
  18792. /**
  18793. * Returns the latest update of the World matrix
  18794. * Returns a Matrix.
  18795. */
  18796. TransformNode.prototype.getWorldMatrix = function () {
  18797. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18798. this.computeWorldMatrix();
  18799. }
  18800. return this._worldMatrix;
  18801. };
  18802. /** @hidden */
  18803. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18804. return this._worldMatrixDeterminant;
  18805. };
  18806. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18807. /**
  18808. * Returns directly the latest state of the mesh World matrix.
  18809. * A Matrix is returned.
  18810. */
  18811. get: function () {
  18812. return this._worldMatrix;
  18813. },
  18814. enumerable: true,
  18815. configurable: true
  18816. });
  18817. /**
  18818. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18819. * Returns the TransformNode.
  18820. */
  18821. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18822. this._poseMatrix.copyFrom(matrix);
  18823. return this;
  18824. };
  18825. /**
  18826. * Returns the mesh Pose matrix.
  18827. * Returned object : Matrix
  18828. */
  18829. TransformNode.prototype.getPoseMatrix = function () {
  18830. return this._poseMatrix;
  18831. };
  18832. TransformNode.prototype._isSynchronized = function () {
  18833. if (this._isDirty) {
  18834. return false;
  18835. }
  18836. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18837. return false;
  18838. if (this._cache.pivotMatrixUpdated) {
  18839. return false;
  18840. }
  18841. if (this.infiniteDistance) {
  18842. return false;
  18843. }
  18844. if (!this._cache.position.equals(this.position))
  18845. return false;
  18846. if (this.rotationQuaternion) {
  18847. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18848. return false;
  18849. }
  18850. if (!this._cache.rotation.equals(this.rotation))
  18851. return false;
  18852. if (!this._cache.scaling.equals(this.scaling))
  18853. return false;
  18854. return true;
  18855. };
  18856. TransformNode.prototype._initCache = function () {
  18857. _super.prototype._initCache.call(this);
  18858. this._cache.localMatrixUpdated = false;
  18859. this._cache.position = BABYLON.Vector3.Zero();
  18860. this._cache.scaling = BABYLON.Vector3.Zero();
  18861. this._cache.rotation = BABYLON.Vector3.Zero();
  18862. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18863. this._cache.billboardMode = -1;
  18864. };
  18865. TransformNode.prototype.markAsDirty = function (property) {
  18866. if (property === "rotation") {
  18867. this.rotationQuaternion = null;
  18868. }
  18869. this._currentRenderId = Number.MAX_VALUE;
  18870. this._isDirty = true;
  18871. return this;
  18872. };
  18873. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18874. /**
  18875. * Returns the current mesh absolute position.
  18876. * Retuns a Vector3.
  18877. */
  18878. get: function () {
  18879. return this._absolutePosition;
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. /**
  18885. * Sets a new matrix to apply before all other transformation
  18886. * @param matrix defines the transform matrix
  18887. * @returns the current TransformNode
  18888. */
  18889. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18890. return this.setPivotMatrix(matrix, false);
  18891. };
  18892. /**
  18893. * Sets a new pivot matrix to the current node
  18894. * @param matrix defines the new pivot matrix to use
  18895. * @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
  18896. * @returns the current TransformNode
  18897. */
  18898. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18899. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18900. this._pivotMatrix = matrix.clone();
  18901. this._cache.pivotMatrixUpdated = true;
  18902. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18903. if (this._postMultiplyPivotMatrix) {
  18904. if (!this._pivotMatrixInverse) {
  18905. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18906. }
  18907. else {
  18908. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18909. }
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Returns the mesh pivot matrix.
  18915. * Default : Identity.
  18916. * A Matrix is returned.
  18917. */
  18918. TransformNode.prototype.getPivotMatrix = function () {
  18919. return this._pivotMatrix;
  18920. };
  18921. /**
  18922. * Prevents the World matrix to be computed any longer.
  18923. * Returns the TransformNode.
  18924. */
  18925. TransformNode.prototype.freezeWorldMatrix = function () {
  18926. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18927. this.computeWorldMatrix(true);
  18928. this._isWorldMatrixFrozen = true;
  18929. return this;
  18930. };
  18931. /**
  18932. * Allows back the World matrix computation.
  18933. * Returns the TransformNode.
  18934. */
  18935. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18936. this._isWorldMatrixFrozen = false;
  18937. this.computeWorldMatrix(true);
  18938. return this;
  18939. };
  18940. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18941. /**
  18942. * True if the World matrix has been frozen.
  18943. * Returns a boolean.
  18944. */
  18945. get: function () {
  18946. return this._isWorldMatrixFrozen;
  18947. },
  18948. enumerable: true,
  18949. configurable: true
  18950. });
  18951. /**
  18952. * Retuns the mesh absolute position in the World.
  18953. * Returns a Vector3.
  18954. */
  18955. TransformNode.prototype.getAbsolutePosition = function () {
  18956. this.computeWorldMatrix();
  18957. return this._absolutePosition;
  18958. };
  18959. /**
  18960. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18961. * Returns the TransformNode.
  18962. */
  18963. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18964. if (!absolutePosition) {
  18965. return this;
  18966. }
  18967. var absolutePositionX;
  18968. var absolutePositionY;
  18969. var absolutePositionZ;
  18970. if (absolutePosition.x === undefined) {
  18971. if (arguments.length < 3) {
  18972. return this;
  18973. }
  18974. absolutePositionX = arguments[0];
  18975. absolutePositionY = arguments[1];
  18976. absolutePositionZ = arguments[2];
  18977. }
  18978. else {
  18979. absolutePositionX = absolutePosition.x;
  18980. absolutePositionY = absolutePosition.y;
  18981. absolutePositionZ = absolutePosition.z;
  18982. }
  18983. if (this.parent) {
  18984. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18985. invertParentWorldMatrix.invert();
  18986. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18987. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18988. }
  18989. else {
  18990. this.position.x = absolutePositionX;
  18991. this.position.y = absolutePositionY;
  18992. this.position.z = absolutePositionZ;
  18993. }
  18994. return this;
  18995. };
  18996. /**
  18997. * Sets the mesh position in its local space.
  18998. * Returns the TransformNode.
  18999. */
  19000. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19001. this.computeWorldMatrix();
  19002. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19003. return this;
  19004. };
  19005. /**
  19006. * Returns the mesh position in the local space from the current World matrix values.
  19007. * Returns a new Vector3.
  19008. */
  19009. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19010. this.computeWorldMatrix();
  19011. var invLocalWorldMatrix = this._localWorld.clone();
  19012. invLocalWorldMatrix.invert();
  19013. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19014. };
  19015. /**
  19016. * Translates the mesh along the passed Vector3 in its local space.
  19017. * Returns the TransformNode.
  19018. */
  19019. TransformNode.prototype.locallyTranslate = function (vector3) {
  19020. this.computeWorldMatrix(true);
  19021. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19022. return this;
  19023. };
  19024. /**
  19025. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19026. * @param targetPoint the position (must be in same space as current mesh) to look at
  19027. * @param yawCor optional yaw (y-axis) correction in radians
  19028. * @param pitchCor optional pitch (x-axis) correction in radians
  19029. * @param rollCor optional roll (z-axis) correction in radians
  19030. * @param space the choosen space of the target
  19031. * @returns the TransformNode.
  19032. */
  19033. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19034. if (yawCor === void 0) { yawCor = 0; }
  19035. if (pitchCor === void 0) { pitchCor = 0; }
  19036. if (rollCor === void 0) { rollCor = 0; }
  19037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19038. var dv = TransformNode._lookAtVectorCache;
  19039. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19040. targetPoint.subtractToRef(pos, dv);
  19041. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19042. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19043. var pitch = Math.atan2(dv.y, len);
  19044. if (this.rotationQuaternion) {
  19045. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19046. }
  19047. else {
  19048. this.rotation.x = pitch + pitchCor;
  19049. this.rotation.y = yaw + yawCor;
  19050. this.rotation.z = rollCor;
  19051. }
  19052. return this;
  19053. };
  19054. /**
  19055. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19056. * This Vector3 is expressed in the World space.
  19057. */
  19058. TransformNode.prototype.getDirection = function (localAxis) {
  19059. var result = BABYLON.Vector3.Zero();
  19060. this.getDirectionToRef(localAxis, result);
  19061. return result;
  19062. };
  19063. /**
  19064. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19065. * localAxis is expressed in the mesh local space.
  19066. * result is computed in the Wordl space from the mesh World matrix.
  19067. * Returns the TransformNode.
  19068. */
  19069. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19070. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19071. return this;
  19072. };
  19073. /**
  19074. * Sets a new pivot point to the current node
  19075. * @param point defines the new pivot point to use
  19076. * @param space defines if the point is in world or local space (local by default)
  19077. * @returns the current TransformNode
  19078. */
  19079. TransformNode.prototype.setPivotPoint = function (point, space) {
  19080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19081. if (this.getScene().getRenderId() == 0) {
  19082. this.computeWorldMatrix(true);
  19083. }
  19084. var wm = this.getWorldMatrix();
  19085. if (space == BABYLON.Space.WORLD) {
  19086. var tmat = BABYLON.Tmp.Matrix[0];
  19087. wm.invertToRef(tmat);
  19088. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19089. }
  19090. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19091. };
  19092. /**
  19093. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19094. */
  19095. TransformNode.prototype.getPivotPoint = function () {
  19096. var point = BABYLON.Vector3.Zero();
  19097. this.getPivotPointToRef(point);
  19098. return point;
  19099. };
  19100. /**
  19101. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19102. * Returns the TransformNode.
  19103. */
  19104. TransformNode.prototype.getPivotPointToRef = function (result) {
  19105. result.x = -this._pivotMatrix.m[12];
  19106. result.y = -this._pivotMatrix.m[13];
  19107. result.z = -this._pivotMatrix.m[14];
  19108. return this;
  19109. };
  19110. /**
  19111. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19112. */
  19113. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19114. var point = BABYLON.Vector3.Zero();
  19115. this.getAbsolutePivotPointToRef(point);
  19116. return point;
  19117. };
  19118. /**
  19119. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19120. * Returns the TransformNode.
  19121. */
  19122. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19123. result.x = this._pivotMatrix.m[12];
  19124. result.y = this._pivotMatrix.m[13];
  19125. result.z = this._pivotMatrix.m[14];
  19126. this.getPivotPointToRef(result);
  19127. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19128. return this;
  19129. };
  19130. /**
  19131. * Defines the passed node as the parent of the current node.
  19132. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19133. * Returns the TransformNode.
  19134. */
  19135. TransformNode.prototype.setParent = function (node) {
  19136. if (!node && !this.parent) {
  19137. return this;
  19138. }
  19139. if (!node) {
  19140. var rotation = BABYLON.Tmp.Quaternion[0];
  19141. var position = BABYLON.Tmp.Vector3[0];
  19142. var scale = BABYLON.Tmp.Vector3[1];
  19143. if (this.parent && this.parent.computeWorldMatrix) {
  19144. this.parent.computeWorldMatrix(true);
  19145. }
  19146. this.computeWorldMatrix(true);
  19147. this.getWorldMatrix().decompose(scale, rotation, position);
  19148. if (this.rotationQuaternion) {
  19149. this.rotationQuaternion.copyFrom(rotation);
  19150. }
  19151. else {
  19152. rotation.toEulerAnglesToRef(this.rotation);
  19153. }
  19154. this.scaling.x = scale.x;
  19155. this.scaling.y = scale.y;
  19156. this.scaling.z = scale.z;
  19157. this.position.x = position.x;
  19158. this.position.y = position.y;
  19159. this.position.z = position.z;
  19160. }
  19161. else {
  19162. var rotation = BABYLON.Tmp.Quaternion[0];
  19163. var position = BABYLON.Tmp.Vector3[0];
  19164. var scale = BABYLON.Tmp.Vector3[1];
  19165. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19166. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19167. this.computeWorldMatrix(true);
  19168. node.computeWorldMatrix(true);
  19169. node.getWorldMatrix().invertToRef(invParentMatrix);
  19170. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19171. diffMatrix.decompose(scale, rotation, position);
  19172. if (this.rotationQuaternion) {
  19173. this.rotationQuaternion.copyFrom(rotation);
  19174. }
  19175. else {
  19176. rotation.toEulerAnglesToRef(this.rotation);
  19177. }
  19178. this.position.x = position.x;
  19179. this.position.y = position.y;
  19180. this.position.z = position.z;
  19181. this.scaling.x = scale.x;
  19182. this.scaling.y = scale.y;
  19183. this.scaling.z = scale.z;
  19184. }
  19185. this.parent = node;
  19186. return this;
  19187. };
  19188. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19189. get: function () {
  19190. return this._nonUniformScaling;
  19191. },
  19192. enumerable: true,
  19193. configurable: true
  19194. });
  19195. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19196. if (this._nonUniformScaling === value) {
  19197. return false;
  19198. }
  19199. this._nonUniformScaling = value;
  19200. return true;
  19201. };
  19202. /**
  19203. * Attach the current TransformNode to another TransformNode associated with a bone
  19204. * @param bone Bone affecting the TransformNode
  19205. * @param affectedTransformNode TransformNode associated with the bone
  19206. */
  19207. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19208. this._transformToBoneReferal = affectedTransformNode;
  19209. this.parent = bone;
  19210. if (bone.getWorldMatrix().determinant() < 0) {
  19211. this.scalingDeterminant *= -1;
  19212. }
  19213. return this;
  19214. };
  19215. TransformNode.prototype.detachFromBone = function () {
  19216. if (!this.parent) {
  19217. return this;
  19218. }
  19219. if (this.parent.getWorldMatrix().determinant() < 0) {
  19220. this.scalingDeterminant *= -1;
  19221. }
  19222. this._transformToBoneReferal = null;
  19223. this.parent = null;
  19224. return this;
  19225. };
  19226. /**
  19227. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19228. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19229. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19230. * The passed axis is also normalized.
  19231. * Returns the TransformNode.
  19232. */
  19233. TransformNode.prototype.rotate = function (axis, amount, space) {
  19234. axis.normalize();
  19235. if (!this.rotationQuaternion) {
  19236. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19237. this.rotation = BABYLON.Vector3.Zero();
  19238. }
  19239. var rotationQuaternion;
  19240. if (!space || space === BABYLON.Space.LOCAL) {
  19241. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19242. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19243. }
  19244. else {
  19245. if (this.parent) {
  19246. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19247. invertParentWorldMatrix.invert();
  19248. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19249. }
  19250. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19251. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19252. }
  19253. return this;
  19254. };
  19255. /**
  19256. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19257. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19258. * The passed axis is also normalized.
  19259. * Returns the TransformNode.
  19260. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19261. */
  19262. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19263. axis.normalize();
  19264. if (!this.rotationQuaternion) {
  19265. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19266. this.rotation.copyFromFloats(0, 0, 0);
  19267. }
  19268. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19269. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19270. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19271. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19272. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19273. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19274. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19275. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19276. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19277. return this;
  19278. };
  19279. /**
  19280. * Translates the mesh along the axis vector for the passed distance in the given space.
  19281. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19282. * Returns the TransformNode.
  19283. */
  19284. TransformNode.prototype.translate = function (axis, distance, space) {
  19285. var displacementVector = axis.scale(distance);
  19286. if (!space || space === BABYLON.Space.LOCAL) {
  19287. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19288. this.setPositionWithLocalVector(tempV3);
  19289. }
  19290. else {
  19291. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19292. }
  19293. return this;
  19294. };
  19295. /**
  19296. * Adds a rotation step to the mesh current rotation.
  19297. * x, y, z are Euler angles expressed in radians.
  19298. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19299. * This means this rotation is made in the mesh local space only.
  19300. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19301. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19302. * ```javascript
  19303. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19304. * ```
  19305. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19306. * 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.
  19307. * Returns the TransformNode.
  19308. */
  19309. TransformNode.prototype.addRotation = function (x, y, z) {
  19310. var rotationQuaternion;
  19311. if (this.rotationQuaternion) {
  19312. rotationQuaternion = this.rotationQuaternion;
  19313. }
  19314. else {
  19315. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19316. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19317. }
  19318. var accumulation = BABYLON.Tmp.Quaternion[0];
  19319. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19320. rotationQuaternion.multiplyInPlace(accumulation);
  19321. if (!this.rotationQuaternion) {
  19322. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19323. }
  19324. return this;
  19325. };
  19326. /**
  19327. * Computes the mesh World matrix and returns it.
  19328. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19329. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19330. * If the parameter `force`is set to `true`, the actual computation is done.
  19331. * Returns the mesh World Matrix.
  19332. */
  19333. TransformNode.prototype.computeWorldMatrix = function (force) {
  19334. if (this._isWorldMatrixFrozen) {
  19335. return this._worldMatrix;
  19336. }
  19337. if (!force && this.isSynchronized(true)) {
  19338. this._currentRenderId = this.getScene().getRenderId();
  19339. return this._worldMatrix;
  19340. }
  19341. this._cache.position.copyFrom(this.position);
  19342. this._cache.scaling.copyFrom(this.scaling);
  19343. this._cache.pivotMatrixUpdated = false;
  19344. this._cache.billboardMode = this.billboardMode;
  19345. this._currentRenderId = this.getScene().getRenderId();
  19346. this._childRenderId = this.getScene().getRenderId();
  19347. this._isDirty = false;
  19348. // Scaling
  19349. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19350. // Rotation
  19351. //rotate, if quaternion is set and rotation was used
  19352. if (this.rotationQuaternion) {
  19353. var len = this.rotation.length();
  19354. if (len) {
  19355. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19356. this.rotation.copyFromFloats(0, 0, 0);
  19357. }
  19358. }
  19359. if (this.rotationQuaternion) {
  19360. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19361. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19362. }
  19363. else {
  19364. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19365. this._cache.rotation.copyFrom(this.rotation);
  19366. }
  19367. // Translation
  19368. var camera = this.getScene().activeCamera;
  19369. if (this.infiniteDistance && !this.parent && camera) {
  19370. var cameraWorldMatrix = camera.getWorldMatrix();
  19371. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19372. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19373. }
  19374. else {
  19375. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19376. }
  19377. // Composing transformations
  19378. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19379. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19380. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19381. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19382. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19383. // Need to decompose each rotation here
  19384. var currentPosition = BABYLON.Tmp.Vector3[3];
  19385. if (this.parent && this.parent.getWorldMatrix) {
  19386. if (this._transformToBoneReferal) {
  19387. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19388. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19389. }
  19390. else {
  19391. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19392. }
  19393. }
  19394. else {
  19395. currentPosition.copyFrom(this.position);
  19396. }
  19397. currentPosition.subtractInPlace(camera.globalPosition);
  19398. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19399. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19400. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19401. }
  19402. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19403. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19404. }
  19405. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19406. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19407. }
  19408. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19409. }
  19410. else {
  19411. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19412. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19413. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19414. }
  19415. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19416. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19417. }
  19418. // Local world
  19419. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19420. // Parent
  19421. if (this.parent && this.parent.getWorldMatrix) {
  19422. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19423. if (this._transformToBoneReferal) {
  19424. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19425. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19426. }
  19427. else {
  19428. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19429. }
  19430. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19431. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19432. this._worldMatrix.copyFrom(this._localWorld);
  19433. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19434. }
  19435. else {
  19436. if (this._transformToBoneReferal) {
  19437. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19438. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19439. }
  19440. else {
  19441. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19442. }
  19443. }
  19444. this._markSyncedWithParent();
  19445. }
  19446. else {
  19447. this._worldMatrix.copyFrom(this._localWorld);
  19448. }
  19449. // Post multiply inverse of pivotMatrix
  19450. if (this._postMultiplyPivotMatrix) {
  19451. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19452. }
  19453. // Normal matrix
  19454. if (!this.ignoreNonUniformScaling) {
  19455. if (this.scaling.isNonUniform) {
  19456. this._updateNonUniformScalingState(true);
  19457. }
  19458. else if (this.parent && this.parent._nonUniformScaling) {
  19459. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19460. }
  19461. else {
  19462. this._updateNonUniformScalingState(false);
  19463. }
  19464. }
  19465. else {
  19466. this._updateNonUniformScalingState(false);
  19467. }
  19468. this._afterComputeWorldMatrix();
  19469. // Absolute position
  19470. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19471. // Callbacks
  19472. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19473. if (!this._poseMatrix) {
  19474. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19475. }
  19476. // Cache the determinant
  19477. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19478. return this._worldMatrix;
  19479. };
  19480. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19481. };
  19482. /**
  19483. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19484. * @param func: callback function to add
  19485. *
  19486. * Returns the TransformNode.
  19487. */
  19488. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19489. this.onAfterWorldMatrixUpdateObservable.add(func);
  19490. return this;
  19491. };
  19492. /**
  19493. * Removes a registered callback function.
  19494. * Returns the TransformNode.
  19495. */
  19496. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19497. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19498. return this;
  19499. };
  19500. /**
  19501. * Clone the current transform node
  19502. * Returns the new transform node
  19503. * @param name Name of the new clone
  19504. * @param newParent New parent for the clone
  19505. * @param doNotCloneChildren Do not clone children hierarchy
  19506. */
  19507. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19508. var _this = this;
  19509. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19510. result.name = name;
  19511. result.id = name;
  19512. if (newParent) {
  19513. result.parent = newParent;
  19514. }
  19515. if (!doNotCloneChildren) {
  19516. // Children
  19517. var directDescendants = this.getDescendants(true);
  19518. for (var index = 0; index < directDescendants.length; index++) {
  19519. var child = directDescendants[index];
  19520. if (child.clone) {
  19521. child.clone(name + "." + child.name, result);
  19522. }
  19523. }
  19524. }
  19525. return result;
  19526. };
  19527. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19528. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19529. serializationObject.type = this.getClassName();
  19530. // Parent
  19531. if (this.parent) {
  19532. serializationObject.parentId = this.parent.id;
  19533. }
  19534. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19535. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19536. }
  19537. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19538. serializationObject.isEnabled = this.isEnabled();
  19539. // Parent
  19540. if (this.parent) {
  19541. serializationObject.parentId = this.parent.id;
  19542. }
  19543. return serializationObject;
  19544. };
  19545. // Statics
  19546. /**
  19547. * Returns a new TransformNode object parsed from the source provided.
  19548. * The parameter `parsedMesh` is the source.
  19549. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19550. */
  19551. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19552. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19553. if (BABYLON.Tags) {
  19554. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19555. }
  19556. if (parsedTransformNode.localMatrix) {
  19557. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19558. }
  19559. else if (parsedTransformNode.pivotMatrix) {
  19560. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19561. }
  19562. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19563. // Parent
  19564. if (parsedTransformNode.parentId) {
  19565. transformNode._waitingParentId = parsedTransformNode.parentId;
  19566. }
  19567. return transformNode;
  19568. };
  19569. /**
  19570. * Releases resources associated with this transform node.
  19571. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19572. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19573. */
  19574. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19575. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19576. // Animations
  19577. this.getScene().stopAnimation(this);
  19578. // Remove from scene
  19579. this.getScene().removeTransformNode(this);
  19580. this.onAfterWorldMatrixUpdateObservable.clear();
  19581. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19582. };
  19583. // Statics
  19584. TransformNode.BILLBOARDMODE_NONE = 0;
  19585. TransformNode.BILLBOARDMODE_X = 1;
  19586. TransformNode.BILLBOARDMODE_Y = 2;
  19587. TransformNode.BILLBOARDMODE_Z = 4;
  19588. TransformNode.BILLBOARDMODE_ALL = 7;
  19589. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19590. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19591. __decorate([
  19592. BABYLON.serializeAsVector3()
  19593. ], TransformNode.prototype, "_rotation", void 0);
  19594. __decorate([
  19595. BABYLON.serializeAsQuaternion()
  19596. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19597. __decorate([
  19598. BABYLON.serializeAsVector3()
  19599. ], TransformNode.prototype, "_scaling", void 0);
  19600. __decorate([
  19601. BABYLON.serialize()
  19602. ], TransformNode.prototype, "billboardMode", void 0);
  19603. __decorate([
  19604. BABYLON.serialize()
  19605. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19606. __decorate([
  19607. BABYLON.serialize()
  19608. ], TransformNode.prototype, "infiniteDistance", void 0);
  19609. __decorate([
  19610. BABYLON.serialize()
  19611. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19612. __decorate([
  19613. BABYLON.serializeAsVector3()
  19614. ], TransformNode.prototype, "position", void 0);
  19615. return TransformNode;
  19616. }(BABYLON.Node));
  19617. BABYLON.TransformNode = TransformNode;
  19618. })(BABYLON || (BABYLON = {}));
  19619. //# sourceMappingURL=babylon.transformNode.js.map
  19620. var BABYLON;
  19621. (function (BABYLON) {
  19622. /**
  19623. * Class used to store all common mesh properties
  19624. */
  19625. var AbstractMesh = /** @class */ (function (_super) {
  19626. __extends(AbstractMesh, _super);
  19627. // Constructor
  19628. /**
  19629. * Creates a new AbstractMesh
  19630. * @param name defines the name of the mesh
  19631. * @param scene defines the hosting scene
  19632. */
  19633. function AbstractMesh(name, scene) {
  19634. if (scene === void 0) { scene = null; }
  19635. var _this = _super.call(this, name, scene, false) || this;
  19636. _this._facetNb = 0; // facet number
  19637. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19638. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19639. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19640. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19641. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19642. _this._subDiv = {
  19643. max: 1,
  19644. X: 1,
  19645. Y: 1,
  19646. Z: 1
  19647. };
  19648. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19649. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19650. // Events
  19651. /**
  19652. * An event triggered when this mesh collides with another one
  19653. */
  19654. _this.onCollideObservable = new BABYLON.Observable();
  19655. /**
  19656. * An event triggered when the collision's position changes
  19657. */
  19658. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19659. /**
  19660. * An event triggered when material is changed
  19661. */
  19662. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19663. // Properties
  19664. /**
  19665. * Gets or sets the orientation for POV movement & rotation
  19666. */
  19667. _this.definedFacingForward = true;
  19668. /**
  19669. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19670. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19671. * * 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.
  19672. * @see http://doc.babylonjs.com/features/occlusionquery
  19673. */
  19674. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19675. /**
  19676. * 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:
  19677. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19678. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19679. * * 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.
  19680. * @see http://doc.babylonjs.com/features/occlusionquery
  19681. */
  19682. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19683. /**
  19684. * 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.
  19685. * The default value is -1 which means don't break the query and wait till the result
  19686. * @see http://doc.babylonjs.com/features/occlusionquery
  19687. */
  19688. _this.occlusionRetryCount = -1;
  19689. _this._occlusionInternalRetryCounter = 0;
  19690. _this._isOccluded = false;
  19691. _this._isOcclusionQueryInProgress = false;
  19692. _this._visibility = 1.0;
  19693. /** Gets or sets the alpha index used to sort transparent meshes
  19694. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19695. */
  19696. _this.alphaIndex = Number.MAX_VALUE;
  19697. /**
  19698. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19699. */
  19700. _this.isVisible = true;
  19701. /**
  19702. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19703. */
  19704. _this.isPickable = true;
  19705. /**
  19706. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19707. */
  19708. _this.showBoundingBox = false;
  19709. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19710. _this.showSubMeshesBoundingBox = false;
  19711. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19712. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19713. */
  19714. _this.isBlocker = false;
  19715. /**
  19716. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19717. */
  19718. _this.enablePointerMoveEvents = false;
  19719. /**
  19720. * Specifies the rendering group id for this mesh (0 by default)
  19721. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19722. */
  19723. _this.renderingGroupId = 0;
  19724. _this._receiveShadows = false;
  19725. /**
  19726. * Gets or sets a boolean indicating if the outline must be rendered as well
  19727. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19728. */
  19729. _this.renderOutline = false;
  19730. /** Defines color to use when rendering outline */
  19731. _this.outlineColor = BABYLON.Color3.Red();
  19732. /** Define width to use when rendering outline */
  19733. _this.outlineWidth = 0.02;
  19734. /**
  19735. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19736. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19737. */
  19738. _this.renderOverlay = false;
  19739. /** Defines color to use when rendering overlay */
  19740. _this.overlayColor = BABYLON.Color3.Red();
  19741. /** Defines alpha to use when rendering overlay */
  19742. _this.overlayAlpha = 0.5;
  19743. _this._hasVertexAlpha = false;
  19744. _this._useVertexColors = true;
  19745. _this._computeBonesUsingShaders = true;
  19746. _this._numBoneInfluencers = 4;
  19747. _this._applyFog = true;
  19748. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19749. _this.useOctreeForRenderingSelection = true;
  19750. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19751. _this.useOctreeForPicking = true;
  19752. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19753. _this.useOctreeForCollisions = true;
  19754. _this._layerMask = 0x0FFFFFFF;
  19755. /**
  19756. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19757. */
  19758. _this.alwaysSelectAsActiveMesh = false;
  19759. /**
  19760. * Gets or sets the current action manager
  19761. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19762. */
  19763. _this.actionManager = null;
  19764. /**
  19765. * Gets or sets impostor used for physic simulation
  19766. * @see http://doc.babylonjs.com/features/physics_engine
  19767. */
  19768. _this.physicsImpostor = null;
  19769. // Collisions
  19770. _this._checkCollisions = false;
  19771. _this._collisionMask = -1;
  19772. _this._collisionGroup = -1;
  19773. /**
  19774. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19775. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19776. */
  19777. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19778. /**
  19779. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19780. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19781. */
  19782. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19783. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19784. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19785. // Edges
  19786. /**
  19787. * Defines edge width used when edgesRenderer is enabled
  19788. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19789. */
  19790. _this.edgesWidth = 1;
  19791. /**
  19792. * Defines edge color used when edgesRenderer is enabled
  19793. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19794. */
  19795. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19796. // Cache
  19797. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19798. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19799. /** @hidden */
  19800. _this._renderId = 0;
  19801. /** @hidden */
  19802. _this._intersectionsInProgress = new Array();
  19803. /** @hidden */
  19804. _this._unIndexed = false;
  19805. /** @hidden */
  19806. _this._lightSources = new Array();
  19807. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19808. if (collidedMesh === void 0) { collidedMesh = null; }
  19809. //TODO move this to the collision coordinator!
  19810. if (_this.getScene().workerCollisions)
  19811. newPosition.multiplyInPlace(_this._collider._radius);
  19812. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19813. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19814. _this.position.addInPlace(_this._diffPositionForCollisions);
  19815. }
  19816. if (collidedMesh) {
  19817. _this.onCollideObservable.notifyObservers(collidedMesh);
  19818. }
  19819. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19820. };
  19821. _this.getScene().addMesh(_this);
  19822. _this._resyncLightSources();
  19823. return _this;
  19824. }
  19825. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19826. /**
  19827. * No billboard
  19828. */
  19829. get: function () {
  19830. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19836. /** Billboard on X axis */
  19837. get: function () {
  19838. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19844. /** Billboard on Y axis */
  19845. get: function () {
  19846. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19852. /** Billboard on Z axis */
  19853. get: function () {
  19854. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19860. /** Billboard on all axes */
  19861. get: function () {
  19862. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19868. /**
  19869. * Gets the number of facets in the mesh
  19870. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19871. */
  19872. get: function () {
  19873. return this._facetNb;
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19879. /**
  19880. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19881. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19882. */
  19883. get: function () {
  19884. return this._partitioningSubdivisions;
  19885. },
  19886. set: function (nb) {
  19887. this._partitioningSubdivisions = nb;
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19893. /**
  19894. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19895. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19896. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19897. */
  19898. get: function () {
  19899. return this._partitioningBBoxRatio;
  19900. },
  19901. set: function (ratio) {
  19902. this._partitioningBBoxRatio = ratio;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19908. /**
  19909. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19910. * Works only for updatable meshes.
  19911. * Doesn't work with multi-materials
  19912. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19913. */
  19914. get: function () {
  19915. return this._facetDepthSort;
  19916. },
  19917. set: function (sort) {
  19918. this._facetDepthSort = sort;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19924. /**
  19925. * The location (Vector3) where the facet depth sort must be computed from.
  19926. * By default, the active camera position.
  19927. * Used only when facet depth sort is enabled
  19928. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19929. */
  19930. get: function () {
  19931. return this._facetDepthSortFrom;
  19932. },
  19933. set: function (location) {
  19934. this._facetDepthSortFrom = location;
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19940. /**
  19941. * gets a boolean indicating if facetData is enabled
  19942. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19943. */
  19944. get: function () {
  19945. return this._facetDataEnabled;
  19946. },
  19947. enumerable: true,
  19948. configurable: true
  19949. });
  19950. /** @hidden */
  19951. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19952. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19953. return false;
  19954. }
  19955. this._markSubMeshesAsMiscDirty();
  19956. return true;
  19957. };
  19958. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19959. /** Set a function to call when this mesh collides with another one */
  19960. set: function (callback) {
  19961. if (this._onCollideObserver) {
  19962. this.onCollideObservable.remove(this._onCollideObserver);
  19963. }
  19964. this._onCollideObserver = this.onCollideObservable.add(callback);
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19970. /** Set a function to call when the collision's position changes */
  19971. set: function (callback) {
  19972. if (this._onCollisionPositionChangeObserver) {
  19973. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19974. }
  19975. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19981. /**
  19982. * 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
  19983. * @see http://doc.babylonjs.com/features/occlusionquery
  19984. */
  19985. get: function () {
  19986. return this._isOccluded;
  19987. },
  19988. set: function (value) {
  19989. this._isOccluded = value;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19995. /**
  19996. * Flag to check the progress status of the query
  19997. * @see http://doc.babylonjs.com/features/occlusionquery
  19998. */
  19999. get: function () {
  20000. return this._isOcclusionQueryInProgress;
  20001. },
  20002. enumerable: true,
  20003. configurable: true
  20004. });
  20005. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20006. /**
  20007. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20008. */
  20009. get: function () {
  20010. return this._visibility;
  20011. },
  20012. /**
  20013. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20014. */
  20015. set: function (value) {
  20016. if (this._visibility === value) {
  20017. return;
  20018. }
  20019. this._visibility = value;
  20020. this._markSubMeshesAsMiscDirty();
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Object.defineProperty(AbstractMesh.prototype, "material", {
  20026. /** Gets or sets current material */
  20027. get: function () {
  20028. return this._material;
  20029. },
  20030. set: function (value) {
  20031. if (this._material === value) {
  20032. return;
  20033. }
  20034. this._material = value;
  20035. if (this.onMaterialChangedObservable.hasObservers) {
  20036. this.onMaterialChangedObservable.notifyObservers(this);
  20037. }
  20038. if (!this.subMeshes) {
  20039. return;
  20040. }
  20041. this._unBindEffect();
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20047. /**
  20048. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20049. * @see http://doc.babylonjs.com/babylon101/shadows
  20050. */
  20051. get: function () {
  20052. return this._receiveShadows;
  20053. },
  20054. set: function (value) {
  20055. if (this._receiveShadows === value) {
  20056. return;
  20057. }
  20058. this._receiveShadows = value;
  20059. this._markSubMeshesAsLightDirty();
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20065. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20066. get: function () {
  20067. return this._hasVertexAlpha;
  20068. },
  20069. set: function (value) {
  20070. if (this._hasVertexAlpha === value) {
  20071. return;
  20072. }
  20073. this._hasVertexAlpha = value;
  20074. this._markSubMeshesAsAttributesDirty();
  20075. this._markSubMeshesAsMiscDirty();
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20081. /** 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) */
  20082. get: function () {
  20083. return this._useVertexColors;
  20084. },
  20085. set: function (value) {
  20086. if (this._useVertexColors === value) {
  20087. return;
  20088. }
  20089. this._useVertexColors = value;
  20090. this._markSubMeshesAsAttributesDirty();
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20096. /**
  20097. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20098. */
  20099. get: function () {
  20100. return this._computeBonesUsingShaders;
  20101. },
  20102. set: function (value) {
  20103. if (this._computeBonesUsingShaders === value) {
  20104. return;
  20105. }
  20106. this._computeBonesUsingShaders = value;
  20107. this._markSubMeshesAsAttributesDirty();
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20113. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20114. get: function () {
  20115. return this._numBoneInfluencers;
  20116. },
  20117. set: function (value) {
  20118. if (this._numBoneInfluencers === value) {
  20119. return;
  20120. }
  20121. this._numBoneInfluencers = value;
  20122. this._markSubMeshesAsAttributesDirty();
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20128. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20129. get: function () {
  20130. return this._applyFog;
  20131. },
  20132. set: function (value) {
  20133. if (this._applyFog === value) {
  20134. return;
  20135. }
  20136. this._applyFog = value;
  20137. this._markSubMeshesAsMiscDirty();
  20138. },
  20139. enumerable: true,
  20140. configurable: true
  20141. });
  20142. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20143. /**
  20144. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20145. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20146. */
  20147. get: function () {
  20148. return this._layerMask;
  20149. },
  20150. set: function (value) {
  20151. if (value === this._layerMask) {
  20152. return;
  20153. }
  20154. this._layerMask = value;
  20155. this._resyncLightSources();
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20161. /**
  20162. * Gets or sets a collision mask used to mask collisions (default is -1).
  20163. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20164. */
  20165. get: function () {
  20166. return this._collisionMask;
  20167. },
  20168. set: function (mask) {
  20169. this._collisionMask = !isNaN(mask) ? mask : -1;
  20170. },
  20171. enumerable: true,
  20172. configurable: true
  20173. });
  20174. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20175. /**
  20176. * Gets or sets the current collision group mask (-1 by default).
  20177. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20178. */
  20179. get: function () {
  20180. return this._collisionGroup;
  20181. },
  20182. set: function (mask) {
  20183. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20189. /** @hidden */
  20190. get: function () {
  20191. return null;
  20192. },
  20193. enumerable: true,
  20194. configurable: true
  20195. });
  20196. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20197. get: function () {
  20198. return this._skeleton;
  20199. },
  20200. /**
  20201. * Gets or sets a skeleton to apply skining transformations
  20202. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20203. */
  20204. set: function (value) {
  20205. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20206. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20207. }
  20208. if (value && value.needInitialSkinMatrix) {
  20209. value._registerMeshWithPoseMatrix(this);
  20210. }
  20211. this._skeleton = value;
  20212. if (!this._skeleton) {
  20213. this._bonesTransformMatrices = null;
  20214. }
  20215. this._markSubMeshesAsAttributesDirty();
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. /**
  20221. * Returns the string "AbstractMesh"
  20222. * @returns "AbstractMesh"
  20223. */
  20224. AbstractMesh.prototype.getClassName = function () {
  20225. return "AbstractMesh";
  20226. };
  20227. /**
  20228. * Gets a string representation of the current mesh
  20229. * @param fullDetails defines a boolean indicating if full details must be included
  20230. * @returns a string representation of the current mesh
  20231. */
  20232. AbstractMesh.prototype.toString = function (fullDetails) {
  20233. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20234. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20235. if (this._skeleton) {
  20236. ret += ", skeleton: " + this._skeleton.name;
  20237. }
  20238. if (fullDetails) {
  20239. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20240. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20241. }
  20242. return ret;
  20243. };
  20244. /** @hidden */
  20245. AbstractMesh.prototype._rebuild = function () {
  20246. if (this._occlusionQuery) {
  20247. this._occlusionQuery = null;
  20248. }
  20249. if (this._edgesRenderer) {
  20250. this._edgesRenderer._rebuild();
  20251. }
  20252. if (!this.subMeshes) {
  20253. return;
  20254. }
  20255. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20256. var subMesh = _a[_i];
  20257. subMesh._rebuild();
  20258. }
  20259. };
  20260. /** @hidden */
  20261. AbstractMesh.prototype._resyncLightSources = function () {
  20262. this._lightSources.length = 0;
  20263. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20264. var light = _a[_i];
  20265. if (!light.isEnabled()) {
  20266. continue;
  20267. }
  20268. if (light.canAffectMesh(this)) {
  20269. this._lightSources.push(light);
  20270. }
  20271. }
  20272. this._markSubMeshesAsLightDirty();
  20273. };
  20274. /** @hidden */
  20275. AbstractMesh.prototype._resyncLighSource = function (light) {
  20276. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20277. var index = this._lightSources.indexOf(light);
  20278. if (index === -1) {
  20279. if (!isIn) {
  20280. return;
  20281. }
  20282. this._lightSources.push(light);
  20283. }
  20284. else {
  20285. if (isIn) {
  20286. return;
  20287. }
  20288. this._lightSources.splice(index, 1);
  20289. }
  20290. this._markSubMeshesAsLightDirty();
  20291. };
  20292. /** @hidden */
  20293. AbstractMesh.prototype._unBindEffect = function () {
  20294. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20295. var subMesh = _a[_i];
  20296. subMesh.setEffect(null);
  20297. }
  20298. };
  20299. /** @hidden */
  20300. AbstractMesh.prototype._removeLightSource = function (light) {
  20301. var index = this._lightSources.indexOf(light);
  20302. if (index === -1) {
  20303. return;
  20304. }
  20305. this._lightSources.splice(index, 1);
  20306. this._markSubMeshesAsLightDirty();
  20307. };
  20308. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20309. if (!this.subMeshes) {
  20310. return;
  20311. }
  20312. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20313. var subMesh = _a[_i];
  20314. if (subMesh._materialDefines) {
  20315. func(subMesh._materialDefines);
  20316. }
  20317. }
  20318. };
  20319. /** @hidden */
  20320. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20321. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20322. };
  20323. /** @hidden */
  20324. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20325. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20326. };
  20327. /** @hidden */
  20328. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20329. if (!this.subMeshes) {
  20330. return;
  20331. }
  20332. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20333. var subMesh = _a[_i];
  20334. var material = subMesh.getMaterial();
  20335. if (material) {
  20336. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20337. }
  20338. }
  20339. };
  20340. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20341. /**
  20342. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20343. */
  20344. get: function () {
  20345. return this._scaling;
  20346. },
  20347. set: function (newScaling) {
  20348. this._scaling = newScaling;
  20349. if (this.physicsImpostor) {
  20350. this.physicsImpostor.forceUpdate();
  20351. }
  20352. },
  20353. enumerable: true,
  20354. configurable: true
  20355. });
  20356. // Methods
  20357. /**
  20358. * Disables the mesh edge rendering mode
  20359. * @returns the currentAbstractMesh
  20360. */
  20361. AbstractMesh.prototype.disableEdgesRendering = function () {
  20362. if (this._edgesRenderer) {
  20363. this._edgesRenderer.dispose();
  20364. this._edgesRenderer = null;
  20365. }
  20366. return this;
  20367. };
  20368. /**
  20369. * Enables the edge rendering mode on the mesh.
  20370. * This mode makes the mesh edges visible
  20371. * @param epsilon defines the maximal distance between two angles to detect a face
  20372. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20373. * @returns the currentAbstractMesh
  20374. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20375. */
  20376. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20377. if (epsilon === void 0) { epsilon = 0.95; }
  20378. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20379. this.disableEdgesRendering();
  20380. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20381. return this;
  20382. };
  20383. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20384. /**
  20385. * Gets the edgesRenderer associated with the mesh
  20386. */
  20387. get: function () {
  20388. return this._edgesRenderer;
  20389. },
  20390. enumerable: true,
  20391. configurable: true
  20392. });
  20393. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20394. /**
  20395. * Returns true if the mesh is blocked. Implemented by child classes
  20396. */
  20397. get: function () {
  20398. return false;
  20399. },
  20400. enumerable: true,
  20401. configurable: true
  20402. });
  20403. /**
  20404. * Returns the mesh itself by default. Implemented by child classes
  20405. * @param camera defines the camera to use to pick the right LOD level
  20406. * @returns the currentAbstractMesh
  20407. */
  20408. AbstractMesh.prototype.getLOD = function (camera) {
  20409. return this;
  20410. };
  20411. /**
  20412. * Returns 0 by default. Implemented by child classes
  20413. * @returns an integer
  20414. */
  20415. AbstractMesh.prototype.getTotalVertices = function () {
  20416. return 0;
  20417. };
  20418. /**
  20419. * Returns null by default. Implemented by child classes
  20420. * @returns null
  20421. */
  20422. AbstractMesh.prototype.getIndices = function () {
  20423. return null;
  20424. };
  20425. /**
  20426. * Returns the array of the requested vertex data kind. Implemented by child classes
  20427. * @param kind defines the vertex data kind to use
  20428. * @returns null
  20429. */
  20430. AbstractMesh.prototype.getVerticesData = function (kind) {
  20431. return null;
  20432. };
  20433. /**
  20434. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20435. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20436. * Note that a new underlying VertexBuffer object is created each call.
  20437. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20438. * @param kind defines vertex data kind:
  20439. * * BABYLON.VertexBuffer.PositionKind
  20440. * * BABYLON.VertexBuffer.UVKind
  20441. * * BABYLON.VertexBuffer.UV2Kind
  20442. * * BABYLON.VertexBuffer.UV3Kind
  20443. * * BABYLON.VertexBuffer.UV4Kind
  20444. * * BABYLON.VertexBuffer.UV5Kind
  20445. * * BABYLON.VertexBuffer.UV6Kind
  20446. * * BABYLON.VertexBuffer.ColorKind
  20447. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20448. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20449. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20450. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20451. * @param data defines the data source
  20452. * @param updatable defines if the data must be flagged as updatable (or static)
  20453. * @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
  20454. * @returns the current mesh
  20455. */
  20456. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20457. return this;
  20458. };
  20459. /**
  20460. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20461. * If the mesh has no geometry, it is simply returned as it is.
  20462. * @param kind defines vertex data kind:
  20463. * * BABYLON.VertexBuffer.PositionKind
  20464. * * BABYLON.VertexBuffer.UVKind
  20465. * * BABYLON.VertexBuffer.UV2Kind
  20466. * * BABYLON.VertexBuffer.UV3Kind
  20467. * * BABYLON.VertexBuffer.UV4Kind
  20468. * * BABYLON.VertexBuffer.UV5Kind
  20469. * * BABYLON.VertexBuffer.UV6Kind
  20470. * * BABYLON.VertexBuffer.ColorKind
  20471. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20472. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20473. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20474. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20475. * @param data defines the data source
  20476. * @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
  20477. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20478. * @returns the current mesh
  20479. */
  20480. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20481. return this;
  20482. };
  20483. /**
  20484. * Sets the mesh indices,
  20485. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20486. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20487. * @param totalVertices Defines the total number of vertices
  20488. * @returns the current mesh
  20489. */
  20490. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20491. return this;
  20492. };
  20493. /**
  20494. * Gets a boolean indicating if specific vertex data is present
  20495. * @param kind defines the vertex data kind to use
  20496. * @returns true is data kind is present
  20497. */
  20498. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20499. return false;
  20500. };
  20501. /**
  20502. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20503. * @returns a BoundingInfo
  20504. */
  20505. AbstractMesh.prototype.getBoundingInfo = function () {
  20506. if (this._masterMesh) {
  20507. return this._masterMesh.getBoundingInfo();
  20508. }
  20509. if (!this._boundingInfo) {
  20510. // this._boundingInfo is being created here
  20511. this._updateBoundingInfo();
  20512. }
  20513. // cannot be null.
  20514. return this._boundingInfo;
  20515. };
  20516. /**
  20517. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20518. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20519. * @returns the current mesh
  20520. */
  20521. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20522. if (includeDescendants === void 0) { includeDescendants = true; }
  20523. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20524. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20525. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20526. if (maxDimension === 0) {
  20527. return this;
  20528. }
  20529. var scale = 1 / maxDimension;
  20530. this.scaling.scaleInPlace(scale);
  20531. return this;
  20532. };
  20533. /**
  20534. * Overwrite the current bounding info
  20535. * @param boundingInfo defines the new bounding info
  20536. * @returns the current mesh
  20537. */
  20538. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20539. this._boundingInfo = boundingInfo;
  20540. return this;
  20541. };
  20542. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20543. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20544. get: function () {
  20545. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. /** @hidden */
  20551. AbstractMesh.prototype._preActivate = function () {
  20552. };
  20553. /** @hidden */
  20554. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20555. };
  20556. /** @hidden */
  20557. AbstractMesh.prototype._activate = function (renderId) {
  20558. this._renderId = renderId;
  20559. };
  20560. /**
  20561. * Gets the current world matrix
  20562. * @returns a Matrix
  20563. */
  20564. AbstractMesh.prototype.getWorldMatrix = function () {
  20565. if (this._masterMesh) {
  20566. return this._masterMesh.getWorldMatrix();
  20567. }
  20568. return _super.prototype.getWorldMatrix.call(this);
  20569. };
  20570. /** @hidden */
  20571. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20572. if (this._masterMesh) {
  20573. return this._masterMesh._getWorldMatrixDeterminant();
  20574. }
  20575. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20576. };
  20577. // ================================== Point of View Movement =================================
  20578. /**
  20579. * Perform relative position change from the point of view of behind the front of the mesh.
  20580. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20581. * Supports definition of mesh facing forward or backward
  20582. * @param amountRight defines the distance on the right axis
  20583. * @param amountUp defines the distance on the up axis
  20584. * @param amountForward defines the distance on the forward axis
  20585. * @returns the current mesh
  20586. */
  20587. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20588. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20589. return this;
  20590. };
  20591. /**
  20592. * Calculate relative position change from the point of view of behind the front of the mesh.
  20593. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20594. * Supports definition of mesh facing forward or backward
  20595. * @param amountRight defines the distance on the right axis
  20596. * @param amountUp defines the distance on the up axis
  20597. * @param amountForward defines the distance on the forward axis
  20598. * @returns the new displacement vector
  20599. */
  20600. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20601. var rotMatrix = new BABYLON.Matrix();
  20602. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20603. rotQuaternion.toRotationMatrix(rotMatrix);
  20604. var translationDelta = BABYLON.Vector3.Zero();
  20605. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20606. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20607. return translationDelta;
  20608. };
  20609. // ================================== Point of View Rotation =================================
  20610. /**
  20611. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20612. * Supports definition of mesh facing forward or backward
  20613. * @param flipBack defines the flip
  20614. * @param twirlClockwise defines the twirl
  20615. * @param tiltRight defines the tilt
  20616. * @returns the current mesh
  20617. */
  20618. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20619. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20620. return this;
  20621. };
  20622. /**
  20623. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20624. * Supports definition of mesh facing forward or backward.
  20625. * @param flipBack defines the flip
  20626. * @param twirlClockwise defines the twirl
  20627. * @param tiltRight defines the tilt
  20628. * @returns the new rotation vector
  20629. */
  20630. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20631. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20632. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20633. };
  20634. /**
  20635. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20636. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20637. * @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
  20638. * @returns the new bounding vectors
  20639. */
  20640. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20641. if (includeDescendants === void 0) { includeDescendants = true; }
  20642. if (predicate === void 0) { predicate = null; }
  20643. // Ensures that all world matrix will be recomputed.
  20644. this.getScene().incrementRenderId();
  20645. this.computeWorldMatrix(true);
  20646. var min;
  20647. var max;
  20648. var boundingInfo = this.getBoundingInfo();
  20649. if (!this.subMeshes) {
  20650. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20651. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20652. }
  20653. else {
  20654. min = boundingInfo.boundingBox.minimumWorld;
  20655. max = boundingInfo.boundingBox.maximumWorld;
  20656. }
  20657. if (includeDescendants) {
  20658. var descendants = this.getDescendants(false);
  20659. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20660. var descendant = descendants_1[_i];
  20661. var childMesh = descendant;
  20662. childMesh.computeWorldMatrix(true);
  20663. // Filters meshes based on custom predicate function.
  20664. if (predicate && !predicate(childMesh)) {
  20665. continue;
  20666. }
  20667. //make sure we have the needed params to get mix and max
  20668. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20669. continue;
  20670. }
  20671. var childBoundingInfo = childMesh.getBoundingInfo();
  20672. var boundingBox = childBoundingInfo.boundingBox;
  20673. var minBox = boundingBox.minimumWorld;
  20674. var maxBox = boundingBox.maximumWorld;
  20675. BABYLON.Tools.CheckExtends(minBox, min, max);
  20676. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20677. }
  20678. }
  20679. return {
  20680. min: min,
  20681. max: max
  20682. };
  20683. };
  20684. /** @hidden */
  20685. AbstractMesh.prototype._updateBoundingInfo = function () {
  20686. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20687. this._boundingInfo.update(this.worldMatrixFromCache);
  20688. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20689. return this;
  20690. };
  20691. /** @hidden */
  20692. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20693. if (!this.subMeshes) {
  20694. return this;
  20695. }
  20696. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20697. var subMesh = this.subMeshes[subIndex];
  20698. if (!subMesh.IsGlobal) {
  20699. subMesh.updateBoundingInfo(matrix);
  20700. }
  20701. }
  20702. return this;
  20703. };
  20704. /** @hidden */
  20705. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20706. // Bounding info
  20707. this._updateBoundingInfo();
  20708. };
  20709. /**
  20710. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20711. * A mesh is in the frustum if its bounding box intersects the frustum
  20712. * @param frustumPlanes defines the frustum to test
  20713. * @returns true if the mesh is in the frustum planes
  20714. */
  20715. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20716. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20717. };
  20718. /**
  20719. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20720. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20721. * @param frustumPlanes defines the frustum to test
  20722. * @returns true if the mesh is completely in the frustum planes
  20723. */
  20724. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20725. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20726. };
  20727. /**
  20728. * True if the mesh intersects another mesh or a SolidParticle object
  20729. * @param mesh defines a target mesh or SolidParticle to test
  20730. * @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)
  20731. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20732. * @returns true if there is an intersection
  20733. */
  20734. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20735. if (precise === void 0) { precise = false; }
  20736. if (!this._boundingInfo || !mesh._boundingInfo) {
  20737. return false;
  20738. }
  20739. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20740. return true;
  20741. }
  20742. if (includeDescendants) {
  20743. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20744. var child = _a[_i];
  20745. if (child.intersectsMesh(mesh, precise, true)) {
  20746. return true;
  20747. }
  20748. }
  20749. }
  20750. return false;
  20751. };
  20752. /**
  20753. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20754. * @param point defines the point to test
  20755. * @returns true if there is an intersection
  20756. */
  20757. AbstractMesh.prototype.intersectsPoint = function (point) {
  20758. if (!this._boundingInfo) {
  20759. return false;
  20760. }
  20761. return this._boundingInfo.intersectsPoint(point);
  20762. };
  20763. /**
  20764. * Gets the current physics impostor
  20765. * @see http://doc.babylonjs.com/features/physics_engine
  20766. * @returns a physics impostor or null
  20767. */
  20768. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20769. return this.physicsImpostor;
  20770. };
  20771. /**
  20772. * Gets the position of the current mesh in camera space
  20773. * @param camera defines the camera to use
  20774. * @returns a position
  20775. */
  20776. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20777. if (camera === void 0) { camera = null; }
  20778. if (!camera) {
  20779. camera = this.getScene().activeCamera;
  20780. }
  20781. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20782. };
  20783. /**
  20784. * Returns the distance from the mesh to the active camera
  20785. * @param camera defines the camera to use
  20786. * @returns the distance
  20787. */
  20788. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20789. if (camera === void 0) { camera = null; }
  20790. if (!camera) {
  20791. camera = this.getScene().activeCamera;
  20792. }
  20793. return this.absolutePosition.subtract(camera.position).length();
  20794. };
  20795. /**
  20796. * Apply a physic impulse to the mesh
  20797. * @param force defines the force to apply
  20798. * @param contactPoint defines where to apply the force
  20799. * @returns the current mesh
  20800. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20801. */
  20802. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20803. if (!this.physicsImpostor) {
  20804. return this;
  20805. }
  20806. this.physicsImpostor.applyImpulse(force, contactPoint);
  20807. return this;
  20808. };
  20809. /**
  20810. * Creates a physic joint between two meshes
  20811. * @param otherMesh defines the other mesh to use
  20812. * @param pivot1 defines the pivot to use on this mesh
  20813. * @param pivot2 defines the pivot to use on the other mesh
  20814. * @param options defines additional options (can be plugin dependent)
  20815. * @returns the current mesh
  20816. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20817. */
  20818. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20819. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20820. return this;
  20821. }
  20822. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20823. mainPivot: pivot1,
  20824. connectedPivot: pivot2,
  20825. nativeParams: options
  20826. });
  20827. return this;
  20828. };
  20829. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20830. // Collisions
  20831. /**
  20832. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20834. */
  20835. get: function () {
  20836. return this._checkCollisions;
  20837. },
  20838. set: function (collisionEnabled) {
  20839. this._checkCollisions = collisionEnabled;
  20840. if (this.getScene().workerCollisions) {
  20841. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20842. }
  20843. },
  20844. enumerable: true,
  20845. configurable: true
  20846. });
  20847. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20848. /**
  20849. * Gets Collider object used to compute collisions (not physics)
  20850. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20851. */
  20852. get: function () {
  20853. return this._collider;
  20854. },
  20855. enumerable: true,
  20856. configurable: true
  20857. });
  20858. /**
  20859. * Move the mesh using collision engine
  20860. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20861. * @param displacement defines the requested displacement vector
  20862. * @returns the current mesh
  20863. */
  20864. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20865. var globalPosition = this.getAbsolutePosition();
  20866. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20867. if (!this._collider) {
  20868. this._collider = new BABYLON.Collider();
  20869. }
  20870. this._collider._radius = this.ellipsoid;
  20871. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20872. return this;
  20873. };
  20874. // Submeshes octree
  20875. /**
  20876. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20877. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20878. * @param maxCapacity defines the maximum size of each block (64 by default)
  20879. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20880. * @returns the new octree
  20881. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20882. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20883. */
  20884. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20885. if (maxCapacity === void 0) { maxCapacity = 64; }
  20886. if (maxDepth === void 0) { maxDepth = 2; }
  20887. if (!this._submeshesOctree) {
  20888. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20889. }
  20890. this.computeWorldMatrix(true);
  20891. var boundingInfo = this.getBoundingInfo();
  20892. // Update octree
  20893. var bbox = boundingInfo.boundingBox;
  20894. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20895. return this._submeshesOctree;
  20896. };
  20897. // Collisions
  20898. /** @hidden */
  20899. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20900. this._generatePointsArray();
  20901. if (!this._positions) {
  20902. return this;
  20903. }
  20904. // Transformation
  20905. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20906. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20907. subMesh._lastColliderWorldVertices = [];
  20908. subMesh._trianglePlanes = [];
  20909. var start = subMesh.verticesStart;
  20910. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20911. for (var i = start; i < end; i++) {
  20912. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20913. }
  20914. }
  20915. // Collide
  20916. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20917. if (collider.collisionFound) {
  20918. collider.collidedMesh = this;
  20919. }
  20920. return this;
  20921. };
  20922. /** @hidden */
  20923. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20924. var subMeshes;
  20925. var len;
  20926. // Octrees
  20927. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20928. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20929. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20930. len = intersections.length;
  20931. subMeshes = intersections.data;
  20932. }
  20933. else {
  20934. subMeshes = this.subMeshes;
  20935. len = subMeshes.length;
  20936. }
  20937. for (var index = 0; index < len; index++) {
  20938. var subMesh = subMeshes[index];
  20939. // Bounding test
  20940. if (len > 1 && !subMesh._checkCollision(collider))
  20941. continue;
  20942. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20943. }
  20944. return this;
  20945. };
  20946. /** @hidden */
  20947. AbstractMesh.prototype._checkCollision = function (collider) {
  20948. // Bounding box test
  20949. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20950. return this;
  20951. // Transformation matrix
  20952. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20953. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20954. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20955. return this;
  20956. };
  20957. // Picking
  20958. /** @hidden */
  20959. AbstractMesh.prototype._generatePointsArray = function () {
  20960. return false;
  20961. };
  20962. /**
  20963. * Checks if the passed Ray intersects with the mesh
  20964. * @param ray defines the ray to use
  20965. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20966. * @returns the picking info
  20967. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20968. */
  20969. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20970. var pickingInfo = new BABYLON.PickingInfo();
  20971. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20972. return pickingInfo;
  20973. }
  20974. if (!this._generatePointsArray()) {
  20975. return pickingInfo;
  20976. }
  20977. var intersectInfo = null;
  20978. // Octrees
  20979. var subMeshes;
  20980. var len;
  20981. if (this._submeshesOctree && this.useOctreeForPicking) {
  20982. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20983. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20984. len = intersections.length;
  20985. subMeshes = intersections.data;
  20986. }
  20987. else {
  20988. subMeshes = this.subMeshes;
  20989. len = subMeshes.length;
  20990. }
  20991. for (var index = 0; index < len; index++) {
  20992. var subMesh = subMeshes[index];
  20993. // Bounding test
  20994. if (len > 1 && !subMesh.canIntersects(ray))
  20995. continue;
  20996. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20997. if (currentIntersectInfo) {
  20998. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20999. intersectInfo = currentIntersectInfo;
  21000. intersectInfo.subMeshId = index;
  21001. if (fastCheck) {
  21002. break;
  21003. }
  21004. }
  21005. }
  21006. }
  21007. if (intersectInfo) {
  21008. // Get picked point
  21009. var world = this.getWorldMatrix();
  21010. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21011. var direction = ray.direction.clone();
  21012. direction = direction.scale(intersectInfo.distance);
  21013. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21014. var pickedPoint = worldOrigin.add(worldDirection);
  21015. // Return result
  21016. pickingInfo.hit = true;
  21017. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21018. pickingInfo.pickedPoint = pickedPoint;
  21019. pickingInfo.pickedMesh = this;
  21020. pickingInfo.bu = intersectInfo.bu || 0;
  21021. pickingInfo.bv = intersectInfo.bv || 0;
  21022. pickingInfo.faceId = intersectInfo.faceId;
  21023. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21024. return pickingInfo;
  21025. }
  21026. return pickingInfo;
  21027. };
  21028. /**
  21029. * Clones the current mesh
  21030. * @param name defines the mesh name
  21031. * @param newParent defines the new mesh parent
  21032. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21033. * @returns the new mesh
  21034. */
  21035. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21036. return null;
  21037. };
  21038. /**
  21039. * Disposes all the submeshes of the current meshnp
  21040. * @returns the current mesh
  21041. */
  21042. AbstractMesh.prototype.releaseSubMeshes = function () {
  21043. if (this.subMeshes) {
  21044. while (this.subMeshes.length) {
  21045. this.subMeshes[0].dispose();
  21046. }
  21047. }
  21048. else {
  21049. this.subMeshes = new Array();
  21050. }
  21051. return this;
  21052. };
  21053. /**
  21054. * Releases resources associated with this abstract mesh.
  21055. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21056. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21057. */
  21058. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21059. var _this = this;
  21060. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21061. var index;
  21062. // Smart Array Retainers.
  21063. this.getScene().freeActiveMeshes();
  21064. this.getScene().freeRenderingGroups();
  21065. // Action manager
  21066. if (this.actionManager !== undefined && this.actionManager !== null) {
  21067. this.actionManager.dispose();
  21068. this.actionManager = null;
  21069. }
  21070. // Skeleton
  21071. this._skeleton = null;
  21072. // Physics
  21073. if (this.physicsImpostor) {
  21074. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21075. }
  21076. // Intersections in progress
  21077. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21078. var other = this._intersectionsInProgress[index];
  21079. var pos = other._intersectionsInProgress.indexOf(this);
  21080. other._intersectionsInProgress.splice(pos, 1);
  21081. }
  21082. this._intersectionsInProgress = [];
  21083. // Lights
  21084. var lights = this.getScene().lights;
  21085. lights.forEach(function (light) {
  21086. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21087. if (meshIndex !== -1) {
  21088. light.includedOnlyMeshes.splice(meshIndex, 1);
  21089. }
  21090. meshIndex = light.excludedMeshes.indexOf(_this);
  21091. if (meshIndex !== -1) {
  21092. light.excludedMeshes.splice(meshIndex, 1);
  21093. }
  21094. // Shadow generators
  21095. var generator = light.getShadowGenerator();
  21096. if (generator) {
  21097. var shadowMap = generator.getShadowMap();
  21098. if (shadowMap && shadowMap.renderList) {
  21099. meshIndex = shadowMap.renderList.indexOf(_this);
  21100. if (meshIndex !== -1) {
  21101. shadowMap.renderList.splice(meshIndex, 1);
  21102. }
  21103. }
  21104. }
  21105. });
  21106. // Edges
  21107. if (this._edgesRenderer) {
  21108. this._edgesRenderer.dispose();
  21109. this._edgesRenderer = null;
  21110. }
  21111. // SubMeshes
  21112. if (this.getClassName() !== "InstancedMesh") {
  21113. this.releaseSubMeshes();
  21114. }
  21115. // Octree
  21116. var sceneOctree = this.getScene().selectionOctree;
  21117. if (sceneOctree !== undefined && sceneOctree !== null) {
  21118. var index = sceneOctree.dynamicContent.indexOf(this);
  21119. if (index !== -1) {
  21120. sceneOctree.dynamicContent.splice(index, 1);
  21121. }
  21122. }
  21123. // Query
  21124. var engine = this.getScene().getEngine();
  21125. if (this._occlusionQuery) {
  21126. this._isOcclusionQueryInProgress = false;
  21127. engine.deleteQuery(this._occlusionQuery);
  21128. this._occlusionQuery = null;
  21129. }
  21130. // Engine
  21131. engine.wipeCaches();
  21132. // Remove from scene
  21133. this.getScene().removeMesh(this);
  21134. if (disposeMaterialAndTextures) {
  21135. if (this.material) {
  21136. this.material.dispose(false, true);
  21137. }
  21138. }
  21139. if (!doNotRecurse) {
  21140. // Particles
  21141. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21142. if (this.getScene().particleSystems[index].emitter === this) {
  21143. this.getScene().particleSystems[index].dispose();
  21144. index--;
  21145. }
  21146. }
  21147. }
  21148. // facet data
  21149. if (this._facetDataEnabled) {
  21150. this.disableFacetData();
  21151. }
  21152. this.onAfterWorldMatrixUpdateObservable.clear();
  21153. this.onCollideObservable.clear();
  21154. this.onCollisionPositionChangeObservable.clear();
  21155. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21156. };
  21157. /**
  21158. * Adds the passed mesh as a child to the current mesh
  21159. * @param mesh defines the child mesh
  21160. * @returns the current mesh
  21161. */
  21162. AbstractMesh.prototype.addChild = function (mesh) {
  21163. mesh.setParent(this);
  21164. return this;
  21165. };
  21166. /**
  21167. * Removes the passed mesh from the current mesh children list
  21168. * @param mesh defines the child mesh
  21169. * @returns the current mesh
  21170. */
  21171. AbstractMesh.prototype.removeChild = function (mesh) {
  21172. mesh.setParent(null);
  21173. return this;
  21174. };
  21175. // Facet data
  21176. /** @hidden */
  21177. AbstractMesh.prototype._initFacetData = function () {
  21178. if (!this._facetNormals) {
  21179. this._facetNormals = new Array();
  21180. }
  21181. if (!this._facetPositions) {
  21182. this._facetPositions = new Array();
  21183. }
  21184. if (!this._facetPartitioning) {
  21185. this._facetPartitioning = new Array();
  21186. }
  21187. this._facetNb = (this.getIndices().length / 3) | 0;
  21188. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21189. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21190. for (var f = 0; f < this._facetNb; f++) {
  21191. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21192. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21193. }
  21194. this._facetDataEnabled = true;
  21195. return this;
  21196. };
  21197. /**
  21198. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21199. * This method can be called within the render loop.
  21200. * 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
  21201. * @returns the current mesh
  21202. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21203. */
  21204. AbstractMesh.prototype.updateFacetData = function () {
  21205. if (!this._facetDataEnabled) {
  21206. this._initFacetData();
  21207. }
  21208. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21209. var indices = this.getIndices();
  21210. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21211. var bInfo = this.getBoundingInfo();
  21212. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21213. // init arrays, matrix and sort function on first call
  21214. this._facetDepthSortEnabled = true;
  21215. if (indices instanceof Uint16Array) {
  21216. this._depthSortedIndices = new Uint16Array(indices);
  21217. }
  21218. else if (indices instanceof Uint32Array) {
  21219. this._depthSortedIndices = new Uint32Array(indices);
  21220. }
  21221. else {
  21222. var needs32bits = false;
  21223. for (var i = 0; i < indices.length; i++) {
  21224. if (indices[i] > 65535) {
  21225. needs32bits = true;
  21226. break;
  21227. }
  21228. }
  21229. if (needs32bits) {
  21230. this._depthSortedIndices = new Uint32Array(indices);
  21231. }
  21232. else {
  21233. this._depthSortedIndices = new Uint16Array(indices);
  21234. }
  21235. }
  21236. this._facetDepthSortFunction = function (f1, f2) {
  21237. return (f2.sqDistance - f1.sqDistance);
  21238. };
  21239. if (!this._facetDepthSortFrom) {
  21240. var camera = this.getScene().activeCamera;
  21241. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21242. }
  21243. this._depthSortedFacets = [];
  21244. for (var f = 0; f < this._facetNb; f++) {
  21245. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21246. this._depthSortedFacets.push(depthSortedFacet);
  21247. }
  21248. this._invertedMatrix = BABYLON.Matrix.Identity();
  21249. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21250. }
  21251. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21252. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21253. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21254. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21255. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21256. this._subDiv.max = this._partitioningSubdivisions;
  21257. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21258. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21259. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21260. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21261. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21262. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21263. // set the parameters for ComputeNormals()
  21264. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21265. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21266. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21267. this._facetParameters.bInfo = bInfo;
  21268. this._facetParameters.bbSize = this._bbSize;
  21269. this._facetParameters.subDiv = this._subDiv;
  21270. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21271. this._facetParameters.depthSort = this._facetDepthSort;
  21272. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21273. this.computeWorldMatrix(true);
  21274. this._worldMatrix.invertToRef(this._invertedMatrix);
  21275. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21276. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21277. }
  21278. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21279. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21280. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21281. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21282. var l = (this._depthSortedIndices.length / 3) | 0;
  21283. for (var f = 0; f < l; f++) {
  21284. var sind = this._depthSortedFacets[f].ind;
  21285. this._depthSortedIndices[f * 3] = indices[sind];
  21286. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21287. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21288. }
  21289. this.updateIndices(this._depthSortedIndices);
  21290. }
  21291. return this;
  21292. };
  21293. /**
  21294. * Returns the facetLocalNormals array.
  21295. * The normals are expressed in the mesh local spac
  21296. * @returns an array of Vector3
  21297. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21298. */
  21299. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21300. if (!this._facetNormals) {
  21301. this.updateFacetData();
  21302. }
  21303. return this._facetNormals;
  21304. };
  21305. /**
  21306. * Returns the facetLocalPositions array.
  21307. * The facet positions are expressed in the mesh local space
  21308. * @returns an array of Vector3
  21309. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21310. */
  21311. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21312. if (!this._facetPositions) {
  21313. this.updateFacetData();
  21314. }
  21315. return this._facetPositions;
  21316. };
  21317. /**
  21318. * Returns the facetLocalPartioning array
  21319. * @returns an array of array of numbers
  21320. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21321. */
  21322. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21323. if (!this._facetPartitioning) {
  21324. this.updateFacetData();
  21325. }
  21326. return this._facetPartitioning;
  21327. };
  21328. /**
  21329. * Returns the i-th facet position in the world system.
  21330. * This method allocates a new Vector3 per call
  21331. * @param i defines the facet index
  21332. * @returns a new Vector3
  21333. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21334. */
  21335. AbstractMesh.prototype.getFacetPosition = function (i) {
  21336. var pos = BABYLON.Vector3.Zero();
  21337. this.getFacetPositionToRef(i, pos);
  21338. return pos;
  21339. };
  21340. /**
  21341. * Sets the reference Vector3 with the i-th facet position in the world system
  21342. * @param i defines the facet index
  21343. * @param ref defines the target vector
  21344. * @returns the current mesh
  21345. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21346. */
  21347. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21348. var localPos = (this.getFacetLocalPositions())[i];
  21349. var world = this.getWorldMatrix();
  21350. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21351. return this;
  21352. };
  21353. /**
  21354. * Returns the i-th facet normal in the world system.
  21355. * This method allocates a new Vector3 per call
  21356. * @param i defines the facet index
  21357. * @returns a new Vector3
  21358. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21359. */
  21360. AbstractMesh.prototype.getFacetNormal = function (i) {
  21361. var norm = BABYLON.Vector3.Zero();
  21362. this.getFacetNormalToRef(i, norm);
  21363. return norm;
  21364. };
  21365. /**
  21366. * Sets the reference Vector3 with the i-th facet normal in the world system
  21367. * @param i defines the facet index
  21368. * @param ref defines the target vector
  21369. * @returns the current mesh
  21370. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21371. */
  21372. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21373. var localNorm = (this.getFacetLocalNormals())[i];
  21374. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21375. return this;
  21376. };
  21377. /**
  21378. * 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)
  21379. * @param x defines x coordinate
  21380. * @param y defines y coordinate
  21381. * @param z defines z coordinate
  21382. * @returns the array of facet indexes
  21383. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21384. */
  21385. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21386. var bInfo = this.getBoundingInfo();
  21387. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21388. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21389. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21390. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21391. return null;
  21392. }
  21393. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21394. };
  21395. /**
  21396. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21397. * @param projected sets as the (x,y,z) world projection on the facet
  21398. * @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
  21399. * @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
  21400. * @param x defines x coordinate
  21401. * @param y defines y coordinate
  21402. * @param z defines z coordinate
  21403. * @returns the face index if found (or null instead)
  21404. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21405. */
  21406. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21407. if (checkFace === void 0) { checkFace = false; }
  21408. if (facing === void 0) { facing = true; }
  21409. var world = this.getWorldMatrix();
  21410. var invMat = BABYLON.Tmp.Matrix[5];
  21411. world.invertToRef(invMat);
  21412. var invVect = BABYLON.Tmp.Vector3[8];
  21413. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21414. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21415. if (projected) {
  21416. // tranform the local computed projected vector to world coordinates
  21417. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21418. }
  21419. return closest;
  21420. };
  21421. /**
  21422. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21423. * @param projected sets as the (x,y,z) local projection on the facet
  21424. * @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
  21425. * @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
  21426. * @param x defines x coordinate
  21427. * @param y defines y coordinate
  21428. * @param z defines z coordinate
  21429. * @returns the face index if found (or null instead)
  21430. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21431. */
  21432. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21433. if (checkFace === void 0) { checkFace = false; }
  21434. if (facing === void 0) { facing = true; }
  21435. var closest = null;
  21436. var tmpx = 0.0;
  21437. var tmpy = 0.0;
  21438. var tmpz = 0.0;
  21439. var d = 0.0; // tmp dot facet normal * facet position
  21440. var t0 = 0.0;
  21441. var projx = 0.0;
  21442. var projy = 0.0;
  21443. var projz = 0.0;
  21444. // Get all the facets in the same partitioning block than (x, y, z)
  21445. var facetPositions = this.getFacetLocalPositions();
  21446. var facetNormals = this.getFacetLocalNormals();
  21447. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21448. if (!facetsInBlock) {
  21449. return null;
  21450. }
  21451. // Get the closest facet to (x, y, z)
  21452. var shortest = Number.MAX_VALUE; // init distance vars
  21453. var tmpDistance = shortest;
  21454. var fib; // current facet in the block
  21455. var norm; // current facet normal
  21456. var p0; // current facet barycenter position
  21457. // loop on all the facets in the current partitioning block
  21458. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21459. fib = facetsInBlock[idx];
  21460. norm = facetNormals[fib];
  21461. p0 = facetPositions[fib];
  21462. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21463. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21464. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21465. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21466. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21467. projx = x + norm.x * t0;
  21468. projy = y + norm.y * t0;
  21469. projz = z + norm.z * t0;
  21470. tmpx = projx - x;
  21471. tmpy = projy - y;
  21472. tmpz = projz - z;
  21473. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21474. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21475. shortest = tmpDistance;
  21476. closest = fib;
  21477. if (projected) {
  21478. projected.x = projx;
  21479. projected.y = projy;
  21480. projected.z = projz;
  21481. }
  21482. }
  21483. }
  21484. }
  21485. return closest;
  21486. };
  21487. /**
  21488. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21489. * @returns the parameters
  21490. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21491. */
  21492. AbstractMesh.prototype.getFacetDataParameters = function () {
  21493. return this._facetParameters;
  21494. };
  21495. /**
  21496. * Disables the feature FacetData and frees the related memory
  21497. * @returns the current mesh
  21498. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21499. */
  21500. AbstractMesh.prototype.disableFacetData = function () {
  21501. if (this._facetDataEnabled) {
  21502. this._facetDataEnabled = false;
  21503. this._facetPositions = new Array();
  21504. this._facetNormals = new Array();
  21505. this._facetPartitioning = new Array();
  21506. this._facetParameters = null;
  21507. this._depthSortedIndices = new Uint32Array(0);
  21508. }
  21509. return this;
  21510. };
  21511. /**
  21512. * Updates the AbstractMesh indices array
  21513. * @param indices defines the data source
  21514. * @returns the current mesh
  21515. */
  21516. AbstractMesh.prototype.updateIndices = function (indices) {
  21517. return this;
  21518. };
  21519. /**
  21520. * Creates new normals data for the mesh
  21521. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21522. * @returns the current mesh
  21523. */
  21524. AbstractMesh.prototype.createNormals = function (updatable) {
  21525. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21526. var indices = this.getIndices();
  21527. var normals;
  21528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21529. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21530. }
  21531. else {
  21532. normals = [];
  21533. }
  21534. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21535. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21536. return this;
  21537. };
  21538. /**
  21539. * Align the mesh with a normal
  21540. * @param normal defines the normal to use
  21541. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21542. * @returns the current mesh
  21543. */
  21544. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21545. if (!upDirection) {
  21546. upDirection = BABYLON.Axis.Y;
  21547. }
  21548. var axisX = BABYLON.Tmp.Vector3[0];
  21549. var axisZ = BABYLON.Tmp.Vector3[1];
  21550. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21551. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21552. if (this.rotationQuaternion) {
  21553. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21554. }
  21555. else {
  21556. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21557. }
  21558. return this;
  21559. };
  21560. /** @hidden */
  21561. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21562. var engine = this.getEngine();
  21563. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21564. this._isOccluded = false;
  21565. return;
  21566. }
  21567. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21568. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21569. if (isOcclusionQueryAvailable) {
  21570. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21571. this._isOcclusionQueryInProgress = false;
  21572. this._occlusionInternalRetryCounter = 0;
  21573. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21574. }
  21575. else {
  21576. this._occlusionInternalRetryCounter++;
  21577. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21578. this._isOcclusionQueryInProgress = false;
  21579. this._occlusionInternalRetryCounter = 0;
  21580. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21581. // if strict continue the last state of the object.
  21582. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21583. }
  21584. else {
  21585. return;
  21586. }
  21587. }
  21588. }
  21589. var scene = this.getScene();
  21590. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21591. if (!this._occlusionQuery) {
  21592. this._occlusionQuery = engine.createQuery();
  21593. }
  21594. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21595. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21596. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21597. this._isOcclusionQueryInProgress = true;
  21598. };
  21599. /** No occlusion */
  21600. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21601. /** Occlusion set to optimisitic */
  21602. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21603. /** Occlusion set to strict */
  21604. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21605. /** Use an accurante occlusion algorithm */
  21606. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21607. /** Use a conservative occlusion algorithm */
  21608. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21609. return AbstractMesh;
  21610. }(BABYLON.TransformNode));
  21611. BABYLON.AbstractMesh = AbstractMesh;
  21612. })(BABYLON || (BABYLON = {}));
  21613. //# sourceMappingURL=babylon.abstractMesh.js.map
  21614. var BABYLON;
  21615. (function (BABYLON) {
  21616. /**
  21617. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21618. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21619. * 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.
  21620. */
  21621. var Light = /** @class */ (function (_super) {
  21622. __extends(Light, _super);
  21623. /**
  21624. * Creates a Light object in the scene.
  21625. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21626. * @param name The firendly name of the light
  21627. * @param scene The scene the light belongs too
  21628. */
  21629. function Light(name, scene) {
  21630. var _this = _super.call(this, name, scene) || this;
  21631. /**
  21632. * Diffuse gives the basic color to an object.
  21633. */
  21634. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21635. /**
  21636. * Specular produces a highlight color on an object.
  21637. * Note: This is note affecting PBR materials.
  21638. */
  21639. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21640. /**
  21641. * Strength of the light.
  21642. * Note: By default it is define in the framework own unit.
  21643. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21644. */
  21645. _this.intensity = 1.0;
  21646. /**
  21647. * Defines how far from the source the light is impacting in scene units.
  21648. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21649. */
  21650. _this.range = Number.MAX_VALUE;
  21651. /**
  21652. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21653. * of light.
  21654. */
  21655. _this._photometricScale = 1.0;
  21656. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21657. _this._radius = 0.00001;
  21658. /**
  21659. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21660. * exceeding the number allowed of the materials.
  21661. */
  21662. _this.renderPriority = 0;
  21663. _this._shadowEnabled = true;
  21664. _this._excludeWithLayerMask = 0;
  21665. _this._includeOnlyWithLayerMask = 0;
  21666. _this._lightmapMode = 0;
  21667. /**
  21668. * @hidden Internal use only.
  21669. */
  21670. _this._excludedMeshesIds = new Array();
  21671. /**
  21672. * @hidden Internal use only.
  21673. */
  21674. _this._includedOnlyMeshesIds = new Array();
  21675. _this.getScene().addLight(_this);
  21676. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21677. _this._buildUniformLayout();
  21678. _this.includedOnlyMeshes = new Array();
  21679. _this.excludedMeshes = new Array();
  21680. _this._resyncMeshes();
  21681. return _this;
  21682. }
  21683. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21684. /**
  21685. * If every light affecting the material is in this lightmapMode,
  21686. * material.lightmapTexture adds or multiplies
  21687. * (depends on material.useLightmapAsShadowmap)
  21688. * after every other light calculations.
  21689. */
  21690. get: function () {
  21691. return Light._LIGHTMAP_DEFAULT;
  21692. },
  21693. enumerable: true,
  21694. configurable: true
  21695. });
  21696. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21697. /**
  21698. * material.lightmapTexture as only diffuse lighting from this light
  21699. * adds only specular lighting from this light
  21700. * adds dynamic shadows
  21701. */
  21702. get: function () {
  21703. return Light._LIGHTMAP_SPECULAR;
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21709. /**
  21710. * material.lightmapTexture as only lighting
  21711. * no light calculation from this light
  21712. * only adds dynamic shadows from this light
  21713. */
  21714. get: function () {
  21715. return Light._LIGHTMAP_SHADOWSONLY;
  21716. },
  21717. enumerable: true,
  21718. configurable: true
  21719. });
  21720. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21721. /**
  21722. * Each light type uses the default quantity according to its type:
  21723. * point/spot lights use luminous intensity
  21724. * directional lights use illuminance
  21725. */
  21726. get: function () {
  21727. return Light._INTENSITYMODE_AUTOMATIC;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21733. /**
  21734. * lumen (lm)
  21735. */
  21736. get: function () {
  21737. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21743. /**
  21744. * candela (lm/sr)
  21745. */
  21746. get: function () {
  21747. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21753. /**
  21754. * lux (lm/m^2)
  21755. */
  21756. get: function () {
  21757. return Light._INTENSITYMODE_ILLUMINANCE;
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21763. /**
  21764. * nit (cd/m^2)
  21765. */
  21766. get: function () {
  21767. return Light._INTENSITYMODE_LUMINANCE;
  21768. },
  21769. enumerable: true,
  21770. configurable: true
  21771. });
  21772. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21773. /**
  21774. * Light type const id of the point light.
  21775. */
  21776. get: function () {
  21777. return Light._LIGHTTYPEID_POINTLIGHT;
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21783. /**
  21784. * Light type const id of the directional light.
  21785. */
  21786. get: function () {
  21787. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21793. /**
  21794. * Light type const id of the spot light.
  21795. */
  21796. get: function () {
  21797. return Light._LIGHTTYPEID_SPOTLIGHT;
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21803. /**
  21804. * Light type const id of the hemispheric light.
  21805. */
  21806. get: function () {
  21807. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Object.defineProperty(Light.prototype, "intensityMode", {
  21813. /**
  21814. * Gets the photometric scale used to interpret the intensity.
  21815. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21816. */
  21817. get: function () {
  21818. return this._intensityMode;
  21819. },
  21820. /**
  21821. * Sets the photometric scale used to interpret the intensity.
  21822. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21823. */
  21824. set: function (value) {
  21825. this._intensityMode = value;
  21826. this._computePhotometricScale();
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. ;
  21832. ;
  21833. Object.defineProperty(Light.prototype, "radius", {
  21834. /**
  21835. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21836. */
  21837. get: function () {
  21838. return this._radius;
  21839. },
  21840. /**
  21841. * sets the light radius used by PBR Materials to simulate soft area lights.
  21842. */
  21843. set: function (value) {
  21844. this._radius = value;
  21845. this._computePhotometricScale();
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. ;
  21851. ;
  21852. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21853. /**
  21854. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21855. * the current shadow generator.
  21856. */
  21857. get: function () {
  21858. return this._shadowEnabled;
  21859. },
  21860. /**
  21861. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21862. * the current shadow generator.
  21863. */
  21864. set: function (value) {
  21865. if (this._shadowEnabled === value) {
  21866. return;
  21867. }
  21868. this._shadowEnabled = value;
  21869. this._markMeshesAsLightDirty();
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21875. /**
  21876. * Gets the only meshes impacted by this light.
  21877. */
  21878. get: function () {
  21879. return this._includedOnlyMeshes;
  21880. },
  21881. /**
  21882. * Sets the only meshes impacted by this light.
  21883. */
  21884. set: function (value) {
  21885. this._includedOnlyMeshes = value;
  21886. this._hookArrayForIncludedOnly(value);
  21887. },
  21888. enumerable: true,
  21889. configurable: true
  21890. });
  21891. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21892. /**
  21893. * Gets the meshes not impacted by this light.
  21894. */
  21895. get: function () {
  21896. return this._excludedMeshes;
  21897. },
  21898. /**
  21899. * Sets the meshes not impacted by this light.
  21900. */
  21901. set: function (value) {
  21902. this._excludedMeshes = value;
  21903. this._hookArrayForExcluded(value);
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21909. /**
  21910. * Gets the layer id use to find what meshes are not impacted by the light.
  21911. * Inactive if 0
  21912. */
  21913. get: function () {
  21914. return this._excludeWithLayerMask;
  21915. },
  21916. /**
  21917. * Sets the layer id use to find what meshes are not impacted by the light.
  21918. * Inactive if 0
  21919. */
  21920. set: function (value) {
  21921. this._excludeWithLayerMask = value;
  21922. this._resyncMeshes();
  21923. },
  21924. enumerable: true,
  21925. configurable: true
  21926. });
  21927. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21928. /**
  21929. * Gets the layer id use to find what meshes are impacted by the light.
  21930. * Inactive if 0
  21931. */
  21932. get: function () {
  21933. return this._includeOnlyWithLayerMask;
  21934. },
  21935. /**
  21936. * Sets the layer id use to find what meshes are impacted by the light.
  21937. * Inactive if 0
  21938. */
  21939. set: function (value) {
  21940. this._includeOnlyWithLayerMask = value;
  21941. this._resyncMeshes();
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Light.prototype, "lightmapMode", {
  21947. /**
  21948. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21949. */
  21950. get: function () {
  21951. return this._lightmapMode;
  21952. },
  21953. /**
  21954. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21955. */
  21956. set: function (value) {
  21957. if (this._lightmapMode === value) {
  21958. return;
  21959. }
  21960. this._lightmapMode = value;
  21961. this._markMeshesAsLightDirty();
  21962. },
  21963. enumerable: true,
  21964. configurable: true
  21965. });
  21966. /**
  21967. * Returns the string "Light".
  21968. * @returns the class name
  21969. */
  21970. Light.prototype.getClassName = function () {
  21971. return "Light";
  21972. };
  21973. /**
  21974. * Converts the light information to a readable string for debug purpose.
  21975. * @param fullDetails Supports for multiple levels of logging within scene loading
  21976. * @returns the human readable light info
  21977. */
  21978. Light.prototype.toString = function (fullDetails) {
  21979. var ret = "Name: " + this.name;
  21980. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21981. if (this.animations) {
  21982. for (var i = 0; i < this.animations.length; i++) {
  21983. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21984. }
  21985. }
  21986. if (fullDetails) {
  21987. }
  21988. return ret;
  21989. };
  21990. /**
  21991. * Set the enabled state of this node.
  21992. * @param value - the new enabled state
  21993. */
  21994. Light.prototype.setEnabled = function (value) {
  21995. _super.prototype.setEnabled.call(this, value);
  21996. this._resyncMeshes();
  21997. };
  21998. /**
  21999. * Returns the Light associated shadow generator if any.
  22000. * @return the associated shadow generator.
  22001. */
  22002. Light.prototype.getShadowGenerator = function () {
  22003. return this._shadowGenerator;
  22004. };
  22005. /**
  22006. * Returns a Vector3, the absolute light position in the World.
  22007. * @returns the world space position of the light
  22008. */
  22009. Light.prototype.getAbsolutePosition = function () {
  22010. return BABYLON.Vector3.Zero();
  22011. };
  22012. /**
  22013. * Specifies if the light will affect the passed mesh.
  22014. * @param mesh The mesh to test against the light
  22015. * @return true the mesh is affected otherwise, false.
  22016. */
  22017. Light.prototype.canAffectMesh = function (mesh) {
  22018. if (!mesh) {
  22019. return true;
  22020. }
  22021. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22022. return false;
  22023. }
  22024. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22025. return false;
  22026. }
  22027. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22028. return false;
  22029. }
  22030. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22031. return false;
  22032. }
  22033. return true;
  22034. };
  22035. /**
  22036. * Computes and Returns the light World matrix.
  22037. * @returns the world matrix
  22038. */
  22039. Light.prototype.getWorldMatrix = function () {
  22040. this._currentRenderId = this.getScene().getRenderId();
  22041. this._childRenderId = this._currentRenderId;
  22042. var worldMatrix = this._getWorldMatrix();
  22043. if (this.parent && this.parent.getWorldMatrix) {
  22044. if (!this._parentedWorldMatrix) {
  22045. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22046. }
  22047. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22048. this._markSyncedWithParent();
  22049. return this._parentedWorldMatrix;
  22050. }
  22051. return worldMatrix;
  22052. };
  22053. /**
  22054. * Sort function to order lights for rendering.
  22055. * @param a First Light object to compare to second.
  22056. * @param b Second Light object to compare first.
  22057. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22058. */
  22059. Light.CompareLightsPriority = function (a, b) {
  22060. //shadow-casting lights have priority over non-shadow-casting lights
  22061. //the renderPrioirty is a secondary sort criterion
  22062. if (a.shadowEnabled !== b.shadowEnabled) {
  22063. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22064. }
  22065. return b.renderPriority - a.renderPriority;
  22066. };
  22067. /**
  22068. * Releases resources associated with this node.
  22069. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22070. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22071. */
  22072. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22073. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22074. if (this._shadowGenerator) {
  22075. this._shadowGenerator.dispose();
  22076. this._shadowGenerator = null;
  22077. }
  22078. // Animations
  22079. this.getScene().stopAnimation(this);
  22080. // Remove from meshes
  22081. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22082. var mesh = _a[_i];
  22083. mesh._removeLightSource(this);
  22084. }
  22085. this._uniformBuffer.dispose();
  22086. // Remove from scene
  22087. this.getScene().removeLight(this);
  22088. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22089. };
  22090. /**
  22091. * Returns the light type ID (integer).
  22092. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22093. */
  22094. Light.prototype.getTypeID = function () {
  22095. return 0;
  22096. };
  22097. /**
  22098. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22099. * @returns the scaled intensity in intensity mode unit
  22100. */
  22101. Light.prototype.getScaledIntensity = function () {
  22102. return this._photometricScale * this.intensity;
  22103. };
  22104. /**
  22105. * Returns a new Light object, named "name", from the current one.
  22106. * @param name The name of the cloned light
  22107. * @returns the new created light
  22108. */
  22109. Light.prototype.clone = function (name) {
  22110. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22111. if (!constructor) {
  22112. return null;
  22113. }
  22114. return BABYLON.SerializationHelper.Clone(constructor, this);
  22115. };
  22116. /**
  22117. * Serializes the current light into a Serialization object.
  22118. * @returns the serialized object.
  22119. */
  22120. Light.prototype.serialize = function () {
  22121. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22122. // Type
  22123. serializationObject.type = this.getTypeID();
  22124. // Parent
  22125. if (this.parent) {
  22126. serializationObject.parentId = this.parent.id;
  22127. }
  22128. // Inclusion / exclusions
  22129. if (this.excludedMeshes.length > 0) {
  22130. serializationObject.excludedMeshesIds = [];
  22131. this.excludedMeshes.forEach(function (mesh) {
  22132. serializationObject.excludedMeshesIds.push(mesh.id);
  22133. });
  22134. }
  22135. if (this.includedOnlyMeshes.length > 0) {
  22136. serializationObject.includedOnlyMeshesIds = [];
  22137. this.includedOnlyMeshes.forEach(function (mesh) {
  22138. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22139. });
  22140. }
  22141. // Animations
  22142. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22143. serializationObject.ranges = this.serializeAnimationRanges();
  22144. return serializationObject;
  22145. };
  22146. /**
  22147. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22148. * This new light is named "name" and added to the passed scene.
  22149. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22150. * @param name The friendly name of the light
  22151. * @param scene The scene the new light will belong to
  22152. * @returns the constructor function
  22153. */
  22154. Light.GetConstructorFromName = function (type, name, scene) {
  22155. switch (type) {
  22156. case 0:
  22157. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22158. case 1:
  22159. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22160. case 2:
  22161. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22162. case 3:
  22163. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22164. }
  22165. return null;
  22166. };
  22167. /**
  22168. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22169. * @param parsedLight The JSON representation of the light
  22170. * @param scene The scene to create the parsed light in
  22171. * @returns the created light after parsing
  22172. */
  22173. Light.Parse = function (parsedLight, scene) {
  22174. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22175. if (!constructor) {
  22176. return null;
  22177. }
  22178. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22179. // Inclusion / exclusions
  22180. if (parsedLight.excludedMeshesIds) {
  22181. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22182. }
  22183. if (parsedLight.includedOnlyMeshesIds) {
  22184. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22185. }
  22186. // Parent
  22187. if (parsedLight.parentId) {
  22188. light._waitingParentId = parsedLight.parentId;
  22189. }
  22190. // Animations
  22191. if (parsedLight.animations) {
  22192. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22193. var parsedAnimation = parsedLight.animations[animationIndex];
  22194. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22195. }
  22196. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22197. }
  22198. if (parsedLight.autoAnimate) {
  22199. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22200. }
  22201. return light;
  22202. };
  22203. Light.prototype._hookArrayForExcluded = function (array) {
  22204. var _this = this;
  22205. var oldPush = array.push;
  22206. array.push = function () {
  22207. var items = [];
  22208. for (var _i = 0; _i < arguments.length; _i++) {
  22209. items[_i] = arguments[_i];
  22210. }
  22211. var result = oldPush.apply(array, items);
  22212. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22213. var item = items_1[_a];
  22214. item._resyncLighSource(_this);
  22215. }
  22216. return result;
  22217. };
  22218. var oldSplice = array.splice;
  22219. array.splice = function (index, deleteCount) {
  22220. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22221. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22222. var item = deleted_1[_i];
  22223. item._resyncLighSource(_this);
  22224. }
  22225. return deleted;
  22226. };
  22227. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22228. var item = array_1[_i];
  22229. item._resyncLighSource(this);
  22230. }
  22231. };
  22232. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22233. var _this = this;
  22234. var oldPush = array.push;
  22235. array.push = function () {
  22236. var items = [];
  22237. for (var _i = 0; _i < arguments.length; _i++) {
  22238. items[_i] = arguments[_i];
  22239. }
  22240. var result = oldPush.apply(array, items);
  22241. _this._resyncMeshes();
  22242. return result;
  22243. };
  22244. var oldSplice = array.splice;
  22245. array.splice = function (index, deleteCount) {
  22246. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22247. _this._resyncMeshes();
  22248. return deleted;
  22249. };
  22250. this._resyncMeshes();
  22251. };
  22252. Light.prototype._resyncMeshes = function () {
  22253. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22254. var mesh = _a[_i];
  22255. mesh._resyncLighSource(this);
  22256. }
  22257. };
  22258. /**
  22259. * Forces the meshes to update their light related information in their rendering used effects
  22260. * @hidden Internal Use Only
  22261. */
  22262. Light.prototype._markMeshesAsLightDirty = function () {
  22263. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22264. var mesh = _a[_i];
  22265. if (mesh._lightSources.indexOf(this) !== -1) {
  22266. mesh._markSubMeshesAsLightDirty();
  22267. }
  22268. }
  22269. };
  22270. /**
  22271. * Recomputes the cached photometric scale if needed.
  22272. */
  22273. Light.prototype._computePhotometricScale = function () {
  22274. this._photometricScale = this._getPhotometricScale();
  22275. this.getScene().resetCachedMaterial();
  22276. };
  22277. /**
  22278. * Returns the Photometric Scale according to the light type and intensity mode.
  22279. */
  22280. Light.prototype._getPhotometricScale = function () {
  22281. var photometricScale = 0.0;
  22282. var lightTypeID = this.getTypeID();
  22283. //get photometric mode
  22284. var photometricMode = this.intensityMode;
  22285. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22286. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22287. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22288. }
  22289. else {
  22290. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22291. }
  22292. }
  22293. //compute photometric scale
  22294. switch (lightTypeID) {
  22295. case Light.LIGHTTYPEID_POINTLIGHT:
  22296. case Light.LIGHTTYPEID_SPOTLIGHT:
  22297. switch (photometricMode) {
  22298. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22299. photometricScale = 1.0 / (4.0 * Math.PI);
  22300. break;
  22301. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22302. photometricScale = 1.0;
  22303. break;
  22304. case Light.INTENSITYMODE_LUMINANCE:
  22305. photometricScale = this.radius * this.radius;
  22306. break;
  22307. }
  22308. break;
  22309. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22310. switch (photometricMode) {
  22311. case Light.INTENSITYMODE_ILLUMINANCE:
  22312. photometricScale = 1.0;
  22313. break;
  22314. case Light.INTENSITYMODE_LUMINANCE:
  22315. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22316. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22317. var apexAngleRadians = this.radius;
  22318. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22319. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22320. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22321. photometricScale = solidAngle;
  22322. break;
  22323. }
  22324. break;
  22325. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22326. // No fall off in hemisperic light.
  22327. photometricScale = 1.0;
  22328. break;
  22329. }
  22330. return photometricScale;
  22331. };
  22332. /**
  22333. * Reorder the light in the scene according to their defined priority.
  22334. * @hidden Internal Use Only
  22335. */
  22336. Light.prototype._reorderLightsInScene = function () {
  22337. var scene = this.getScene();
  22338. if (this._renderPriority != 0) {
  22339. scene.requireLightSorting = true;
  22340. }
  22341. this.getScene().sortLightsByPriority();
  22342. };
  22343. //lightmapMode Consts
  22344. Light._LIGHTMAP_DEFAULT = 0;
  22345. Light._LIGHTMAP_SPECULAR = 1;
  22346. Light._LIGHTMAP_SHADOWSONLY = 2;
  22347. // Intensity Mode Consts
  22348. Light._INTENSITYMODE_AUTOMATIC = 0;
  22349. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22350. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22351. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22352. Light._INTENSITYMODE_LUMINANCE = 4;
  22353. // Light types ids const.
  22354. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22355. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22356. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22357. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22358. __decorate([
  22359. BABYLON.serializeAsColor3()
  22360. ], Light.prototype, "diffuse", void 0);
  22361. __decorate([
  22362. BABYLON.serializeAsColor3()
  22363. ], Light.prototype, "specular", void 0);
  22364. __decorate([
  22365. BABYLON.serialize()
  22366. ], Light.prototype, "intensity", void 0);
  22367. __decorate([
  22368. BABYLON.serialize()
  22369. ], Light.prototype, "range", void 0);
  22370. __decorate([
  22371. BABYLON.serialize()
  22372. ], Light.prototype, "intensityMode", null);
  22373. __decorate([
  22374. BABYLON.serialize()
  22375. ], Light.prototype, "radius", null);
  22376. __decorate([
  22377. BABYLON.serialize()
  22378. ], Light.prototype, "_renderPriority", void 0);
  22379. __decorate([
  22380. BABYLON.expandToProperty("_reorderLightsInScene")
  22381. ], Light.prototype, "renderPriority", void 0);
  22382. __decorate([
  22383. BABYLON.serialize("shadowEnabled")
  22384. ], Light.prototype, "_shadowEnabled", void 0);
  22385. __decorate([
  22386. BABYLON.serialize("excludeWithLayerMask")
  22387. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22388. __decorate([
  22389. BABYLON.serialize("includeOnlyWithLayerMask")
  22390. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22391. __decorate([
  22392. BABYLON.serialize("lightmapMode")
  22393. ], Light.prototype, "_lightmapMode", void 0);
  22394. return Light;
  22395. }(BABYLON.Node));
  22396. BABYLON.Light = Light;
  22397. })(BABYLON || (BABYLON = {}));
  22398. //# sourceMappingURL=babylon.light.js.map
  22399. var BABYLON;
  22400. (function (BABYLON) {
  22401. var Camera = /** @class */ (function (_super) {
  22402. __extends(Camera, _super);
  22403. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22404. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22405. var _this = _super.call(this, name, scene) || this;
  22406. /**
  22407. * The vector the camera should consider as up.
  22408. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22409. */
  22410. _this.upVector = BABYLON.Vector3.Up();
  22411. _this.orthoLeft = null;
  22412. _this.orthoRight = null;
  22413. _this.orthoBottom = null;
  22414. _this.orthoTop = null;
  22415. /**
  22416. * FOV is set in Radians. (default is 0.8)
  22417. */
  22418. _this.fov = 0.8;
  22419. _this.minZ = 1;
  22420. _this.maxZ = 10000.0;
  22421. _this.inertia = 0.9;
  22422. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22423. _this.isIntermediate = false;
  22424. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22425. /**
  22426. * Restricts the camera to viewing objects with the same layerMask.
  22427. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22428. */
  22429. _this.layerMask = 0x0FFFFFFF;
  22430. /**
  22431. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22432. */
  22433. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22434. // Camera rig members
  22435. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22436. _this._rigCameras = new Array();
  22437. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22438. _this._skipRendering = false;
  22439. _this.customRenderTargets = new Array();
  22440. // Observables
  22441. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22442. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22443. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22444. _this.onRestoreStateObservable = new BABYLON.Observable();
  22445. // Cache
  22446. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22447. _this._projectionMatrix = new BABYLON.Matrix();
  22448. _this._doNotComputeProjectionMatrix = false;
  22449. _this._worldMatrix = BABYLON.Matrix.Identity();
  22450. _this._postProcesses = new Array();
  22451. _this._transformMatrix = BABYLON.Matrix.Zero();
  22452. _this._activeMeshes = new BABYLON.SmartArray(256);
  22453. _this._globalPosition = BABYLON.Vector3.Zero();
  22454. _this._refreshFrustumPlanes = true;
  22455. _this.getScene().addCamera(_this);
  22456. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22457. _this.getScene().activeCamera = _this;
  22458. }
  22459. _this.position = position;
  22460. return _this;
  22461. }
  22462. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22463. get: function () {
  22464. return Camera._PERSPECTIVE_CAMERA;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22470. get: function () {
  22471. return Camera._ORTHOGRAPHIC_CAMERA;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22477. /**
  22478. * This is the default FOV mode for perspective cameras.
  22479. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22480. *
  22481. */
  22482. get: function () {
  22483. return Camera._FOVMODE_VERTICAL_FIXED;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22489. /**
  22490. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22491. *
  22492. */
  22493. get: function () {
  22494. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22500. get: function () {
  22501. return Camera._RIG_MODE_NONE;
  22502. },
  22503. enumerable: true,
  22504. configurable: true
  22505. });
  22506. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22507. get: function () {
  22508. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22509. },
  22510. enumerable: true,
  22511. configurable: true
  22512. });
  22513. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22514. get: function () {
  22515. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22516. },
  22517. enumerable: true,
  22518. configurable: true
  22519. });
  22520. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22521. get: function () {
  22522. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22528. get: function () {
  22529. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22535. get: function () {
  22536. return Camera._RIG_MODE_VR;
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22542. get: function () {
  22543. return Camera._RIG_MODE_WEBVR;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. /**
  22549. * Store current camera state (fov, position, etc..)
  22550. */
  22551. Camera.prototype.storeState = function () {
  22552. this._stateStored = true;
  22553. this._storedFov = this.fov;
  22554. return this;
  22555. };
  22556. /**
  22557. * Restores the camera state values if it has been stored. You must call storeState() first
  22558. */
  22559. Camera.prototype._restoreStateValues = function () {
  22560. if (!this._stateStored) {
  22561. return false;
  22562. }
  22563. this.fov = this._storedFov;
  22564. return true;
  22565. };
  22566. /**
  22567. * Restored camera state. You must call storeState() first
  22568. */
  22569. Camera.prototype.restoreState = function () {
  22570. if (this._restoreStateValues()) {
  22571. this.onRestoreStateObservable.notifyObservers(this);
  22572. return true;
  22573. }
  22574. return false;
  22575. };
  22576. Camera.prototype.getClassName = function () {
  22577. return "Camera";
  22578. };
  22579. /**
  22580. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22581. */
  22582. Camera.prototype.toString = function (fullDetails) {
  22583. var ret = "Name: " + this.name;
  22584. ret += ", type: " + this.getClassName();
  22585. if (this.animations) {
  22586. for (var i = 0; i < this.animations.length; i++) {
  22587. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22588. }
  22589. }
  22590. if (fullDetails) {
  22591. }
  22592. return ret;
  22593. };
  22594. Object.defineProperty(Camera.prototype, "globalPosition", {
  22595. get: function () {
  22596. return this._globalPosition;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Camera.prototype.getActiveMeshes = function () {
  22602. return this._activeMeshes;
  22603. };
  22604. Camera.prototype.isActiveMesh = function (mesh) {
  22605. return (this._activeMeshes.indexOf(mesh) !== -1);
  22606. };
  22607. /**
  22608. * Is this camera ready to be used/rendered
  22609. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22610. * @return true if the camera is ready
  22611. */
  22612. Camera.prototype.isReady = function (completeCheck) {
  22613. if (completeCheck === void 0) { completeCheck = false; }
  22614. if (completeCheck) {
  22615. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22616. var pp = _a[_i];
  22617. if (pp && !pp.isReady()) {
  22618. return false;
  22619. }
  22620. }
  22621. }
  22622. return _super.prototype.isReady.call(this, completeCheck);
  22623. };
  22624. //Cache
  22625. Camera.prototype._initCache = function () {
  22626. _super.prototype._initCache.call(this);
  22627. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22628. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22629. this._cache.mode = undefined;
  22630. this._cache.minZ = undefined;
  22631. this._cache.maxZ = undefined;
  22632. this._cache.fov = undefined;
  22633. this._cache.fovMode = undefined;
  22634. this._cache.aspectRatio = undefined;
  22635. this._cache.orthoLeft = undefined;
  22636. this._cache.orthoRight = undefined;
  22637. this._cache.orthoBottom = undefined;
  22638. this._cache.orthoTop = undefined;
  22639. this._cache.renderWidth = undefined;
  22640. this._cache.renderHeight = undefined;
  22641. };
  22642. Camera.prototype._updateCache = function (ignoreParentClass) {
  22643. if (!ignoreParentClass) {
  22644. _super.prototype._updateCache.call(this);
  22645. }
  22646. this._cache.position.copyFrom(this.position);
  22647. this._cache.upVector.copyFrom(this.upVector);
  22648. };
  22649. // Synchronized
  22650. Camera.prototype._isSynchronized = function () {
  22651. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22652. };
  22653. Camera.prototype._isSynchronizedViewMatrix = function () {
  22654. if (!_super.prototype._isSynchronized.call(this))
  22655. return false;
  22656. return this._cache.position.equals(this.position)
  22657. && this._cache.upVector.equals(this.upVector)
  22658. && this.isSynchronizedWithParent();
  22659. };
  22660. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22661. var check = this._cache.mode === this.mode
  22662. && this._cache.minZ === this.minZ
  22663. && this._cache.maxZ === this.maxZ;
  22664. if (!check) {
  22665. return false;
  22666. }
  22667. var engine = this.getEngine();
  22668. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22669. check = this._cache.fov === this.fov
  22670. && this._cache.fovMode === this.fovMode
  22671. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22672. }
  22673. else {
  22674. check = this._cache.orthoLeft === this.orthoLeft
  22675. && this._cache.orthoRight === this.orthoRight
  22676. && this._cache.orthoBottom === this.orthoBottom
  22677. && this._cache.orthoTop === this.orthoTop
  22678. && this._cache.renderWidth === engine.getRenderWidth()
  22679. && this._cache.renderHeight === engine.getRenderHeight();
  22680. }
  22681. return check;
  22682. };
  22683. // Controls
  22684. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22685. };
  22686. Camera.prototype.detachControl = function (element) {
  22687. };
  22688. Camera.prototype.update = function () {
  22689. this._checkInputs();
  22690. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22691. this._updateRigCameras();
  22692. }
  22693. };
  22694. Camera.prototype._checkInputs = function () {
  22695. this.onAfterCheckInputsObservable.notifyObservers(this);
  22696. };
  22697. Object.defineProperty(Camera.prototype, "rigCameras", {
  22698. get: function () {
  22699. return this._rigCameras;
  22700. },
  22701. enumerable: true,
  22702. configurable: true
  22703. });
  22704. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22705. get: function () {
  22706. return this._rigPostProcess;
  22707. },
  22708. enumerable: true,
  22709. configurable: true
  22710. });
  22711. /**
  22712. * Internal, gets the first post proces.
  22713. * @returns the first post process to be run on this camera.
  22714. */
  22715. Camera.prototype._getFirstPostProcess = function () {
  22716. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22717. if (this._postProcesses[ppIndex] !== null) {
  22718. return this._postProcesses[ppIndex];
  22719. }
  22720. }
  22721. return null;
  22722. };
  22723. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22724. // invalidate framebuffer
  22725. var firstPostProcess = this._getFirstPostProcess();
  22726. if (firstPostProcess) {
  22727. firstPostProcess.markTextureDirty();
  22728. }
  22729. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22730. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22731. var cam = this._rigCameras[i];
  22732. var rigPostProcess = cam._rigPostProcess;
  22733. // for VR rig, there does not have to be a post process
  22734. if (rigPostProcess) {
  22735. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22736. if (isPass) {
  22737. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22738. cam.isIntermediate = this._postProcesses.length === 0;
  22739. }
  22740. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22741. rigPostProcess.markTextureDirty();
  22742. }
  22743. else {
  22744. cam._postProcesses = this._postProcesses.slice(0);
  22745. }
  22746. }
  22747. };
  22748. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22749. if (insertAt === void 0) { insertAt = null; }
  22750. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22751. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22752. return 0;
  22753. }
  22754. if (insertAt == null || insertAt < 0) {
  22755. this._postProcesses.push(postProcess);
  22756. }
  22757. else if (this._postProcesses[insertAt] === null) {
  22758. this._postProcesses[insertAt] = postProcess;
  22759. }
  22760. else {
  22761. this._postProcesses.splice(insertAt, 0, postProcess);
  22762. }
  22763. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22764. return this._postProcesses.indexOf(postProcess);
  22765. };
  22766. Camera.prototype.detachPostProcess = function (postProcess) {
  22767. var idx = this._postProcesses.indexOf(postProcess);
  22768. if (idx !== -1) {
  22769. this._postProcesses[idx] = null;
  22770. }
  22771. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22772. };
  22773. Camera.prototype.getWorldMatrix = function () {
  22774. if (this._isSynchronizedViewMatrix()) {
  22775. return this._worldMatrix;
  22776. }
  22777. // Getting the the view matrix will also compute the world matrix.
  22778. this.getViewMatrix();
  22779. return this._worldMatrix;
  22780. };
  22781. Camera.prototype._getViewMatrix = function () {
  22782. return BABYLON.Matrix.Identity();
  22783. };
  22784. Camera.prototype.getViewMatrix = function (force) {
  22785. if (!force && this._isSynchronizedViewMatrix()) {
  22786. return this._computedViewMatrix;
  22787. }
  22788. this.updateCache();
  22789. this._computedViewMatrix = this._getViewMatrix();
  22790. this._currentRenderId = this.getScene().getRenderId();
  22791. this._childRenderId = this._currentRenderId;
  22792. this._refreshFrustumPlanes = true;
  22793. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22794. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22795. }
  22796. this.onViewMatrixChangedObservable.notifyObservers(this);
  22797. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22798. return this._computedViewMatrix;
  22799. };
  22800. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22801. this._doNotComputeProjectionMatrix = true;
  22802. if (projection !== undefined) {
  22803. this._projectionMatrix = projection;
  22804. }
  22805. };
  22806. ;
  22807. Camera.prototype.unfreezeProjectionMatrix = function () {
  22808. this._doNotComputeProjectionMatrix = false;
  22809. };
  22810. ;
  22811. Camera.prototype.getProjectionMatrix = function (force) {
  22812. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22813. return this._projectionMatrix;
  22814. }
  22815. // Cache
  22816. this._cache.mode = this.mode;
  22817. this._cache.minZ = this.minZ;
  22818. this._cache.maxZ = this.maxZ;
  22819. // Matrix
  22820. this._refreshFrustumPlanes = true;
  22821. var engine = this.getEngine();
  22822. var scene = this.getScene();
  22823. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22824. this._cache.fov = this.fov;
  22825. this._cache.fovMode = this.fovMode;
  22826. this._cache.aspectRatio = engine.getAspectRatio(this);
  22827. if (this.minZ <= 0) {
  22828. this.minZ = 0.1;
  22829. }
  22830. if (scene.useRightHandedSystem) {
  22831. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22832. }
  22833. else {
  22834. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22835. }
  22836. }
  22837. else {
  22838. var halfWidth = engine.getRenderWidth() / 2.0;
  22839. var halfHeight = engine.getRenderHeight() / 2.0;
  22840. if (scene.useRightHandedSystem) {
  22841. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22842. }
  22843. else {
  22844. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22845. }
  22846. this._cache.orthoLeft = this.orthoLeft;
  22847. this._cache.orthoRight = this.orthoRight;
  22848. this._cache.orthoBottom = this.orthoBottom;
  22849. this._cache.orthoTop = this.orthoTop;
  22850. this._cache.renderWidth = engine.getRenderWidth();
  22851. this._cache.renderHeight = engine.getRenderHeight();
  22852. }
  22853. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22854. return this._projectionMatrix;
  22855. };
  22856. Camera.prototype.getTranformationMatrix = function () {
  22857. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22858. return this._transformMatrix;
  22859. };
  22860. Camera.prototype.updateFrustumPlanes = function () {
  22861. if (!this._refreshFrustumPlanes) {
  22862. return;
  22863. }
  22864. this.getTranformationMatrix();
  22865. if (!this._frustumPlanes) {
  22866. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22867. }
  22868. else {
  22869. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22870. }
  22871. this._refreshFrustumPlanes = false;
  22872. };
  22873. Camera.prototype.isInFrustum = function (target) {
  22874. this.updateFrustumPlanes();
  22875. return target.isInFrustum(this._frustumPlanes);
  22876. };
  22877. Camera.prototype.isCompletelyInFrustum = function (target) {
  22878. this.updateFrustumPlanes();
  22879. return target.isCompletelyInFrustum(this._frustumPlanes);
  22880. };
  22881. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22882. if (length === void 0) { length = 100; }
  22883. if (!transform) {
  22884. transform = this.getWorldMatrix();
  22885. }
  22886. if (!origin) {
  22887. origin = this.position;
  22888. }
  22889. var forward = new BABYLON.Vector3(0, 0, 1);
  22890. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22891. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22892. return new BABYLON.Ray(origin, direction, length);
  22893. };
  22894. /**
  22895. * Releases resources associated with this node.
  22896. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22897. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22898. */
  22899. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22900. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22901. // Observables
  22902. this.onViewMatrixChangedObservable.clear();
  22903. this.onProjectionMatrixChangedObservable.clear();
  22904. this.onAfterCheckInputsObservable.clear();
  22905. this.onRestoreStateObservable.clear();
  22906. // Inputs
  22907. if (this.inputs) {
  22908. this.inputs.clear();
  22909. }
  22910. // Animations
  22911. this.getScene().stopAnimation(this);
  22912. // Remove from scene
  22913. this.getScene().removeCamera(this);
  22914. while (this._rigCameras.length > 0) {
  22915. var camera = this._rigCameras.pop();
  22916. if (camera) {
  22917. camera.dispose();
  22918. }
  22919. }
  22920. // Postprocesses
  22921. if (this._rigPostProcess) {
  22922. this._rigPostProcess.dispose(this);
  22923. this._rigPostProcess = null;
  22924. this._postProcesses = [];
  22925. }
  22926. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22927. this._rigPostProcess = null;
  22928. this._postProcesses = [];
  22929. }
  22930. else {
  22931. var i = this._postProcesses.length;
  22932. while (--i >= 0) {
  22933. var postProcess = this._postProcesses[i];
  22934. if (postProcess) {
  22935. postProcess.dispose(this);
  22936. }
  22937. }
  22938. }
  22939. // Render targets
  22940. var i = this.customRenderTargets.length;
  22941. while (--i >= 0) {
  22942. this.customRenderTargets[i].dispose();
  22943. }
  22944. this.customRenderTargets = [];
  22945. // Active Meshes
  22946. this._activeMeshes.dispose();
  22947. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22948. };
  22949. Object.defineProperty(Camera.prototype, "leftCamera", {
  22950. // ---- Camera rigs section ----
  22951. get: function () {
  22952. if (this._rigCameras.length < 1) {
  22953. return null;
  22954. }
  22955. return this._rigCameras[0];
  22956. },
  22957. enumerable: true,
  22958. configurable: true
  22959. });
  22960. Object.defineProperty(Camera.prototype, "rightCamera", {
  22961. get: function () {
  22962. if (this._rigCameras.length < 2) {
  22963. return null;
  22964. }
  22965. return this._rigCameras[1];
  22966. },
  22967. enumerable: true,
  22968. configurable: true
  22969. });
  22970. Camera.prototype.getLeftTarget = function () {
  22971. if (this._rigCameras.length < 1) {
  22972. return null;
  22973. }
  22974. return this._rigCameras[0].getTarget();
  22975. };
  22976. Camera.prototype.getRightTarget = function () {
  22977. if (this._rigCameras.length < 2) {
  22978. return null;
  22979. }
  22980. return this._rigCameras[1].getTarget();
  22981. };
  22982. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22983. if (this.cameraRigMode === mode) {
  22984. return;
  22985. }
  22986. while (this._rigCameras.length > 0) {
  22987. var camera = this._rigCameras.pop();
  22988. if (camera) {
  22989. camera.dispose();
  22990. }
  22991. }
  22992. this.cameraRigMode = mode;
  22993. this._cameraRigParams = {};
  22994. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22995. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22996. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22997. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22998. // create the rig cameras, unless none
  22999. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23000. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23001. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23002. if (leftCamera && rightCamera) {
  23003. this._rigCameras.push(leftCamera);
  23004. this._rigCameras.push(rightCamera);
  23005. }
  23006. }
  23007. switch (this.cameraRigMode) {
  23008. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23009. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23010. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23011. break;
  23012. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23013. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23014. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23015. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23016. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23017. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23018. break;
  23019. case Camera.RIG_MODE_VR:
  23020. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23021. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23022. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23023. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23024. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23025. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23026. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23027. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23028. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23029. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23030. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23031. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23032. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23033. if (metrics.compensateDistortion) {
  23034. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23035. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23036. }
  23037. break;
  23038. case Camera.RIG_MODE_WEBVR:
  23039. if (rigParams.vrDisplay) {
  23040. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23041. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23042. //Left eye
  23043. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23044. this._rigCameras[0].setCameraRigParameter("left", true);
  23045. //leaving this for future reference
  23046. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23047. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23048. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23049. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23050. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23051. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23052. this._rigCameras[0].parent = this;
  23053. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23054. //Right eye
  23055. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23056. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23057. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23058. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23059. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23060. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23061. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23062. this._rigCameras[1].parent = this;
  23063. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23064. if (Camera.UseAlternateWebVRRendering) {
  23065. this._rigCameras[1]._skipRendering = true;
  23066. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23067. }
  23068. }
  23069. break;
  23070. }
  23071. this._cascadePostProcessesToRigCams();
  23072. this.update();
  23073. };
  23074. Camera.prototype._getVRProjectionMatrix = function () {
  23075. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23076. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23077. return this._projectionMatrix;
  23078. };
  23079. Camera.prototype._updateCameraRotationMatrix = function () {
  23080. //Here for WebVR
  23081. };
  23082. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23083. //Here for WebVR
  23084. };
  23085. /**
  23086. * This function MUST be overwritten by the different WebVR cameras available.
  23087. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23088. */
  23089. Camera.prototype._getWebVRProjectionMatrix = function () {
  23090. return BABYLON.Matrix.Identity();
  23091. };
  23092. /**
  23093. * This function MUST be overwritten by the different WebVR cameras available.
  23094. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23095. */
  23096. Camera.prototype._getWebVRViewMatrix = function () {
  23097. return BABYLON.Matrix.Identity();
  23098. };
  23099. Camera.prototype.setCameraRigParameter = function (name, value) {
  23100. if (!this._cameraRigParams) {
  23101. this._cameraRigParams = {};
  23102. }
  23103. this._cameraRigParams[name] = value;
  23104. //provisionnally:
  23105. if (name === "interaxialDistance") {
  23106. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23107. }
  23108. };
  23109. /**
  23110. * needs to be overridden by children so sub has required properties to be copied
  23111. */
  23112. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23113. return null;
  23114. };
  23115. /**
  23116. * May need to be overridden by children
  23117. */
  23118. Camera.prototype._updateRigCameras = function () {
  23119. for (var i = 0; i < this._rigCameras.length; i++) {
  23120. this._rigCameras[i].minZ = this.minZ;
  23121. this._rigCameras[i].maxZ = this.maxZ;
  23122. this._rigCameras[i].fov = this.fov;
  23123. }
  23124. // only update viewport when ANAGLYPH
  23125. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23126. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23127. }
  23128. };
  23129. Camera.prototype._setupInputs = function () {
  23130. };
  23131. Camera.prototype.serialize = function () {
  23132. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23133. // Type
  23134. serializationObject.type = this.getClassName();
  23135. // Parent
  23136. if (this.parent) {
  23137. serializationObject.parentId = this.parent.id;
  23138. }
  23139. if (this.inputs) {
  23140. this.inputs.serialize(serializationObject);
  23141. }
  23142. // Animations
  23143. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23144. serializationObject.ranges = this.serializeAnimationRanges();
  23145. return serializationObject;
  23146. };
  23147. Camera.prototype.clone = function (name) {
  23148. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23149. };
  23150. Camera.prototype.getDirection = function (localAxis) {
  23151. var result = BABYLON.Vector3.Zero();
  23152. this.getDirectionToRef(localAxis, result);
  23153. return result;
  23154. };
  23155. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23156. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23157. };
  23158. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23159. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23160. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23161. switch (type) {
  23162. case "ArcRotateCamera":
  23163. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23164. case "DeviceOrientationCamera":
  23165. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23166. case "FollowCamera":
  23167. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23168. case "ArcFollowCamera":
  23169. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23170. case "GamepadCamera":
  23171. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23172. case "TouchCamera":
  23173. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23174. case "VirtualJoysticksCamera":
  23175. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23176. case "WebVRFreeCamera":
  23177. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23178. case "WebVRGamepadCamera":
  23179. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23180. case "VRDeviceOrientationFreeCamera":
  23181. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23182. case "VRDeviceOrientationGamepadCamera":
  23183. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23184. case "AnaglyphArcRotateCamera":
  23185. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23186. case "AnaglyphFreeCamera":
  23187. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23188. case "AnaglyphGamepadCamera":
  23189. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23190. case "AnaglyphUniversalCamera":
  23191. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23192. case "StereoscopicArcRotateCamera":
  23193. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23194. case "StereoscopicFreeCamera":
  23195. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23196. case "StereoscopicGamepadCamera":
  23197. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23198. case "StereoscopicUniversalCamera":
  23199. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23200. case "FreeCamera": // Forcing Universal here
  23201. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23202. default: // Universal Camera is the default value
  23203. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23204. }
  23205. };
  23206. Camera.prototype.computeWorldMatrix = function () {
  23207. return this.getWorldMatrix();
  23208. };
  23209. Camera.Parse = function (parsedCamera, scene) {
  23210. var type = parsedCamera.type;
  23211. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23212. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23213. // Parent
  23214. if (parsedCamera.parentId) {
  23215. camera._waitingParentId = parsedCamera.parentId;
  23216. }
  23217. //If camera has an input manager, let it parse inputs settings
  23218. if (camera.inputs) {
  23219. camera.inputs.parse(parsedCamera);
  23220. camera._setupInputs();
  23221. }
  23222. if (camera.setPosition) { // need to force position
  23223. camera.position.copyFromFloats(0, 0, 0);
  23224. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23225. }
  23226. // Target
  23227. if (parsedCamera.target) {
  23228. if (camera.setTarget) {
  23229. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23230. }
  23231. }
  23232. // Apply 3d rig, when found
  23233. if (parsedCamera.cameraRigMode) {
  23234. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23235. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23236. }
  23237. // Animations
  23238. if (parsedCamera.animations) {
  23239. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23240. var parsedAnimation = parsedCamera.animations[animationIndex];
  23241. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23242. }
  23243. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23244. }
  23245. if (parsedCamera.autoAnimate) {
  23246. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23247. }
  23248. return camera;
  23249. };
  23250. // Statics
  23251. Camera._PERSPECTIVE_CAMERA = 0;
  23252. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23253. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23254. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23255. Camera._RIG_MODE_NONE = 0;
  23256. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23257. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23258. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23259. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23260. Camera._RIG_MODE_VR = 20;
  23261. Camera._RIG_MODE_WEBVR = 21;
  23262. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23263. Camera.UseAlternateWebVRRendering = false;
  23264. __decorate([
  23265. BABYLON.serializeAsVector3()
  23266. ], Camera.prototype, "position", void 0);
  23267. __decorate([
  23268. BABYLON.serializeAsVector3()
  23269. ], Camera.prototype, "upVector", void 0);
  23270. __decorate([
  23271. BABYLON.serialize()
  23272. ], Camera.prototype, "orthoLeft", void 0);
  23273. __decorate([
  23274. BABYLON.serialize()
  23275. ], Camera.prototype, "orthoRight", void 0);
  23276. __decorate([
  23277. BABYLON.serialize()
  23278. ], Camera.prototype, "orthoBottom", void 0);
  23279. __decorate([
  23280. BABYLON.serialize()
  23281. ], Camera.prototype, "orthoTop", void 0);
  23282. __decorate([
  23283. BABYLON.serialize()
  23284. ], Camera.prototype, "fov", void 0);
  23285. __decorate([
  23286. BABYLON.serialize()
  23287. ], Camera.prototype, "minZ", void 0);
  23288. __decorate([
  23289. BABYLON.serialize()
  23290. ], Camera.prototype, "maxZ", void 0);
  23291. __decorate([
  23292. BABYLON.serialize()
  23293. ], Camera.prototype, "inertia", void 0);
  23294. __decorate([
  23295. BABYLON.serialize()
  23296. ], Camera.prototype, "mode", void 0);
  23297. __decorate([
  23298. BABYLON.serialize()
  23299. ], Camera.prototype, "layerMask", void 0);
  23300. __decorate([
  23301. BABYLON.serialize()
  23302. ], Camera.prototype, "fovMode", void 0);
  23303. __decorate([
  23304. BABYLON.serialize()
  23305. ], Camera.prototype, "cameraRigMode", void 0);
  23306. __decorate([
  23307. BABYLON.serialize()
  23308. ], Camera.prototype, "interaxialDistance", void 0);
  23309. __decorate([
  23310. BABYLON.serialize()
  23311. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23312. return Camera;
  23313. }(BABYLON.Node));
  23314. BABYLON.Camera = Camera;
  23315. })(BABYLON || (BABYLON = {}));
  23316. //# sourceMappingURL=babylon.camera.js.map
  23317. var BABYLON;
  23318. (function (BABYLON) {
  23319. var RenderingManager = /** @class */ (function () {
  23320. function RenderingManager(scene) {
  23321. this._renderingGroups = new Array();
  23322. this._autoClearDepthStencil = {};
  23323. this._customOpaqueSortCompareFn = {};
  23324. this._customAlphaTestSortCompareFn = {};
  23325. this._customTransparentSortCompareFn = {};
  23326. this._renderinGroupInfo = null;
  23327. this._scene = scene;
  23328. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23329. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23330. }
  23331. }
  23332. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23333. if (depth === void 0) { depth = true; }
  23334. if (stencil === void 0) { stencil = true; }
  23335. if (this._depthStencilBufferAlreadyCleaned) {
  23336. return;
  23337. }
  23338. this._scene.getEngine().clear(null, false, depth, stencil);
  23339. this._depthStencilBufferAlreadyCleaned = true;
  23340. };
  23341. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23342. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23343. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23344. var info = null;
  23345. if (observable) {
  23346. if (!this._renderinGroupInfo) {
  23347. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23348. }
  23349. info = this._renderinGroupInfo;
  23350. info.scene = this._scene;
  23351. info.camera = this._scene.activeCamera;
  23352. }
  23353. // Dispatch sprites
  23354. if (renderSprites) {
  23355. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23356. var manager = this._scene.spriteManagers[index];
  23357. this.dispatchSprites(manager);
  23358. }
  23359. }
  23360. // Render
  23361. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23362. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23363. var renderingGroup = this._renderingGroups[index];
  23364. if (!renderingGroup && !observable)
  23365. continue;
  23366. var renderingGroupMask = 0;
  23367. // Fire PRECLEAR stage
  23368. if (observable && info) {
  23369. renderingGroupMask = Math.pow(2, index);
  23370. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23371. info.renderingGroupId = index;
  23372. observable.notifyObservers(info, renderingGroupMask);
  23373. }
  23374. // Clear depth/stencil if needed
  23375. if (RenderingManager.AUTOCLEAR) {
  23376. var autoClear = this._autoClearDepthStencil[index];
  23377. if (autoClear && autoClear.autoClear) {
  23378. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23379. }
  23380. }
  23381. if (observable && info) {
  23382. // Fire PREOPAQUE stage
  23383. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23384. observable.notifyObservers(info, renderingGroupMask);
  23385. // Fire PRETRANSPARENT stage
  23386. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23387. observable.notifyObservers(info, renderingGroupMask);
  23388. }
  23389. if (renderingGroup) {
  23390. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23391. var step = _a[_i];
  23392. step.action(index);
  23393. }
  23394. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23395. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23396. var step = _c[_b];
  23397. step.action(index);
  23398. }
  23399. }
  23400. // Fire POSTTRANSPARENT stage
  23401. if (observable && info) {
  23402. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23403. observable.notifyObservers(info, renderingGroupMask);
  23404. }
  23405. }
  23406. };
  23407. RenderingManager.prototype.reset = function () {
  23408. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23409. var renderingGroup = this._renderingGroups[index];
  23410. if (renderingGroup) {
  23411. renderingGroup.prepare();
  23412. }
  23413. }
  23414. };
  23415. RenderingManager.prototype.dispose = function () {
  23416. this.freeRenderingGroups();
  23417. this._renderingGroups.length = 0;
  23418. };
  23419. /**
  23420. * Clear the info related to rendering groups preventing retention points during dispose.
  23421. */
  23422. RenderingManager.prototype.freeRenderingGroups = function () {
  23423. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23424. var renderingGroup = this._renderingGroups[index];
  23425. if (renderingGroup) {
  23426. renderingGroup.dispose();
  23427. }
  23428. }
  23429. };
  23430. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23431. if (this._renderingGroups[renderingGroupId] === undefined) {
  23432. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23433. }
  23434. };
  23435. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23436. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23437. this._prepareRenderingGroup(renderingGroupId);
  23438. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23439. };
  23440. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23441. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23442. this._prepareRenderingGroup(renderingGroupId);
  23443. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23444. };
  23445. /**
  23446. * @param subMesh The submesh to dispatch
  23447. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23448. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23449. */
  23450. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23451. if (mesh === undefined) {
  23452. mesh = subMesh.getMesh();
  23453. }
  23454. var renderingGroupId = mesh.renderingGroupId || 0;
  23455. this._prepareRenderingGroup(renderingGroupId);
  23456. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23457. };
  23458. /**
  23459. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23460. * This allowed control for front to back rendering or reversly depending of the special needs.
  23461. *
  23462. * @param renderingGroupId The rendering group id corresponding to its index
  23463. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23464. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23465. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23466. */
  23467. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23468. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23469. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23470. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23471. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23472. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23473. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23474. if (this._renderingGroups[renderingGroupId]) {
  23475. var group = this._renderingGroups[renderingGroupId];
  23476. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23477. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23478. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23479. }
  23480. };
  23481. /**
  23482. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23483. *
  23484. * @param renderingGroupId The rendering group id corresponding to its index
  23485. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23486. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23487. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23488. */
  23489. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23490. if (depth === void 0) { depth = true; }
  23491. if (stencil === void 0) { stencil = true; }
  23492. this._autoClearDepthStencil[renderingGroupId] = {
  23493. autoClear: autoClearDepthStencil,
  23494. depth: depth,
  23495. stencil: stencil
  23496. };
  23497. };
  23498. /**
  23499. * The max id used for rendering groups (not included)
  23500. */
  23501. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23502. /**
  23503. * The min id used for rendering groups (included)
  23504. */
  23505. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23506. /**
  23507. * Used to globally prevent autoclearing scenes.
  23508. */
  23509. RenderingManager.AUTOCLEAR = true;
  23510. return RenderingManager;
  23511. }());
  23512. BABYLON.RenderingManager = RenderingManager;
  23513. })(BABYLON || (BABYLON = {}));
  23514. //# sourceMappingURL=babylon.renderingManager.js.map
  23515. var BABYLON;
  23516. (function (BABYLON) {
  23517. var RenderingGroup = /** @class */ (function () {
  23518. /**
  23519. * Creates a new rendering group.
  23520. * @param index The rendering group index
  23521. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23522. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23523. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23524. */
  23525. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23526. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23527. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23528. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23529. this.index = index;
  23530. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23531. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23532. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23533. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23534. this._particleSystems = new BABYLON.SmartArray(256);
  23535. this._spriteManagers = new BABYLON.SmartArray(256);
  23536. this._edgesRenderers = new BABYLON.SmartArray(16);
  23537. this._scene = scene;
  23538. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23539. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23540. this.transparentSortCompareFn = transparentSortCompareFn;
  23541. }
  23542. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23543. /**
  23544. * Set the opaque sort comparison function.
  23545. * If null the sub meshes will be render in the order they were created
  23546. */
  23547. set: function (value) {
  23548. this._opaqueSortCompareFn = value;
  23549. if (value) {
  23550. this._renderOpaque = this.renderOpaqueSorted;
  23551. }
  23552. else {
  23553. this._renderOpaque = RenderingGroup.renderUnsorted;
  23554. }
  23555. },
  23556. enumerable: true,
  23557. configurable: true
  23558. });
  23559. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23560. /**
  23561. * Set the alpha test sort comparison function.
  23562. * If null the sub meshes will be render in the order they were created
  23563. */
  23564. set: function (value) {
  23565. this._alphaTestSortCompareFn = value;
  23566. if (value) {
  23567. this._renderAlphaTest = this.renderAlphaTestSorted;
  23568. }
  23569. else {
  23570. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23571. }
  23572. },
  23573. enumerable: true,
  23574. configurable: true
  23575. });
  23576. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23577. /**
  23578. * Set the transparent sort comparison function.
  23579. * If null the sub meshes will be render in the order they were created
  23580. */
  23581. set: function (value) {
  23582. if (value) {
  23583. this._transparentSortCompareFn = value;
  23584. }
  23585. else {
  23586. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23587. }
  23588. this._renderTransparent = this.renderTransparentSorted;
  23589. },
  23590. enumerable: true,
  23591. configurable: true
  23592. });
  23593. /**
  23594. * Render all the sub meshes contained in the group.
  23595. * @param customRenderFunction Used to override the default render behaviour of the group.
  23596. * @returns true if rendered some submeshes.
  23597. */
  23598. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23599. if (customRenderFunction) {
  23600. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23601. return;
  23602. }
  23603. var engine = this._scene.getEngine();
  23604. // Depth only
  23605. if (this._depthOnlySubMeshes.length !== 0) {
  23606. engine.setColorWrite(false);
  23607. this._renderAlphaTest(this._depthOnlySubMeshes);
  23608. engine.setColorWrite(true);
  23609. }
  23610. // Opaque
  23611. if (this._opaqueSubMeshes.length !== 0) {
  23612. this._renderOpaque(this._opaqueSubMeshes);
  23613. }
  23614. // Alpha test
  23615. if (this._alphaTestSubMeshes.length !== 0) {
  23616. this._renderAlphaTest(this._alphaTestSubMeshes);
  23617. }
  23618. var stencilState = engine.getStencilBuffer();
  23619. engine.setStencilBuffer(false);
  23620. // Sprites
  23621. if (renderSprites) {
  23622. this._renderSprites();
  23623. }
  23624. // Particles
  23625. if (renderParticles) {
  23626. this._renderParticles(activeMeshes);
  23627. }
  23628. if (this.onBeforeTransparentRendering) {
  23629. this.onBeforeTransparentRendering();
  23630. }
  23631. // Transparent
  23632. if (this._transparentSubMeshes.length !== 0) {
  23633. this._renderTransparent(this._transparentSubMeshes);
  23634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23635. }
  23636. // Set back stencil to false in case it changes before the edge renderer.
  23637. engine.setStencilBuffer(false);
  23638. // Edges
  23639. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23640. this._edgesRenderers.data[edgesRendererIndex].render();
  23641. }
  23642. // Restore Stencil state.
  23643. engine.setStencilBuffer(stencilState);
  23644. };
  23645. /**
  23646. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23647. * @param subMeshes The submeshes to render
  23648. */
  23649. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23650. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23651. };
  23652. /**
  23653. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23654. * @param subMeshes The submeshes to render
  23655. */
  23656. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23657. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23658. };
  23659. /**
  23660. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23661. * @param subMeshes The submeshes to render
  23662. */
  23663. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23664. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23665. };
  23666. /**
  23667. * Renders the submeshes in a specified order.
  23668. * @param subMeshes The submeshes to sort before render
  23669. * @param sortCompareFn The comparison function use to sort
  23670. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23671. * @param transparent Specifies to activate blending if true
  23672. */
  23673. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23674. var subIndex = 0;
  23675. var subMesh;
  23676. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23677. for (; subIndex < subMeshes.length; subIndex++) {
  23678. subMesh = subMeshes.data[subIndex];
  23679. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23680. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23681. }
  23682. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23683. if (sortCompareFn) {
  23684. sortedArray.sort(sortCompareFn);
  23685. }
  23686. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23687. subMesh = sortedArray[subIndex];
  23688. if (transparent) {
  23689. var material = subMesh.getMaterial();
  23690. if (material && material.needDepthPrePass) {
  23691. var engine = material.getScene().getEngine();
  23692. engine.setColorWrite(false);
  23693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23694. subMesh.render(false);
  23695. engine.setColorWrite(true);
  23696. }
  23697. }
  23698. subMesh.render(transparent);
  23699. }
  23700. };
  23701. /**
  23702. * Renders the submeshes in the order they were dispatched (no sort applied).
  23703. * @param subMeshes The submeshes to render
  23704. */
  23705. RenderingGroup.renderUnsorted = function (subMeshes) {
  23706. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23707. var submesh = subMeshes.data[subIndex];
  23708. submesh.render(false);
  23709. }
  23710. };
  23711. /**
  23712. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23713. * are rendered back to front if in the same alpha index.
  23714. *
  23715. * @param a The first submesh
  23716. * @param b The second submesh
  23717. * @returns The result of the comparison
  23718. */
  23719. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23720. // Alpha index first
  23721. if (a._alphaIndex > b._alphaIndex) {
  23722. return 1;
  23723. }
  23724. if (a._alphaIndex < b._alphaIndex) {
  23725. return -1;
  23726. }
  23727. // Then distance to camera
  23728. return RenderingGroup.backToFrontSortCompare(a, b);
  23729. };
  23730. /**
  23731. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23732. * are rendered back to front.
  23733. *
  23734. * @param a The first submesh
  23735. * @param b The second submesh
  23736. * @returns The result of the comparison
  23737. */
  23738. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23739. // Then distance to camera
  23740. if (a._distanceToCamera < b._distanceToCamera) {
  23741. return 1;
  23742. }
  23743. if (a._distanceToCamera > b._distanceToCamera) {
  23744. return -1;
  23745. }
  23746. return 0;
  23747. };
  23748. /**
  23749. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23750. * are rendered front to back (prevent overdraw).
  23751. *
  23752. * @param a The first submesh
  23753. * @param b The second submesh
  23754. * @returns The result of the comparison
  23755. */
  23756. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23757. // Then distance to camera
  23758. if (a._distanceToCamera < b._distanceToCamera) {
  23759. return -1;
  23760. }
  23761. if (a._distanceToCamera > b._distanceToCamera) {
  23762. return 1;
  23763. }
  23764. return 0;
  23765. };
  23766. /**
  23767. * Resets the different lists of submeshes to prepare a new frame.
  23768. */
  23769. RenderingGroup.prototype.prepare = function () {
  23770. this._opaqueSubMeshes.reset();
  23771. this._transparentSubMeshes.reset();
  23772. this._alphaTestSubMeshes.reset();
  23773. this._depthOnlySubMeshes.reset();
  23774. this._particleSystems.reset();
  23775. this._spriteManagers.reset();
  23776. this._edgesRenderers.reset();
  23777. };
  23778. RenderingGroup.prototype.dispose = function () {
  23779. this._opaqueSubMeshes.dispose();
  23780. this._transparentSubMeshes.dispose();
  23781. this._alphaTestSubMeshes.dispose();
  23782. this._depthOnlySubMeshes.dispose();
  23783. this._particleSystems.dispose();
  23784. this._spriteManagers.dispose();
  23785. this._edgesRenderers.dispose();
  23786. };
  23787. /**
  23788. * Inserts the submesh in its correct queue depending on its material.
  23789. * @param subMesh The submesh to dispatch
  23790. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23791. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23792. */
  23793. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23794. // Get mesh and materials if not provided
  23795. if (mesh === undefined) {
  23796. mesh = subMesh.getMesh();
  23797. }
  23798. if (material === undefined) {
  23799. material = subMesh.getMaterial();
  23800. }
  23801. if (material === null || material === undefined) {
  23802. return;
  23803. }
  23804. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23805. this._transparentSubMeshes.push(subMesh);
  23806. }
  23807. else if (material.needAlphaTesting()) { // Alpha test
  23808. if (material.needDepthPrePass) {
  23809. this._depthOnlySubMeshes.push(subMesh);
  23810. }
  23811. this._alphaTestSubMeshes.push(subMesh);
  23812. }
  23813. else {
  23814. if (material.needDepthPrePass) {
  23815. this._depthOnlySubMeshes.push(subMesh);
  23816. }
  23817. this._opaqueSubMeshes.push(subMesh); // Opaque
  23818. }
  23819. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23820. this._edgesRenderers.push(mesh._edgesRenderer);
  23821. }
  23822. };
  23823. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23824. this._spriteManagers.push(spriteManager);
  23825. };
  23826. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23827. this._particleSystems.push(particleSystem);
  23828. };
  23829. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23830. if (this._particleSystems.length === 0) {
  23831. return;
  23832. }
  23833. // Particles
  23834. var activeCamera = this._scene.activeCamera;
  23835. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23836. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23837. var particleSystem = this._particleSystems.data[particleIndex];
  23838. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23839. continue;
  23840. }
  23841. var emitter = particleSystem.emitter;
  23842. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23843. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23844. }
  23845. }
  23846. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23847. };
  23848. RenderingGroup.prototype._renderSprites = function () {
  23849. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23850. return;
  23851. }
  23852. // Sprites
  23853. var activeCamera = this._scene.activeCamera;
  23854. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23855. for (var id = 0; id < this._spriteManagers.length; id++) {
  23856. var spriteManager = this._spriteManagers.data[id];
  23857. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23858. spriteManager.render();
  23859. }
  23860. }
  23861. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23862. };
  23863. return RenderingGroup;
  23864. }());
  23865. BABYLON.RenderingGroup = RenderingGroup;
  23866. })(BABYLON || (BABYLON = {}));
  23867. //# sourceMappingURL=babylon.renderingGroup.js.map
  23868. var BABYLON;
  23869. (function (BABYLON) {
  23870. /**
  23871. * Groups all the scene component constants in one place to ease maintenance.
  23872. * @hidden
  23873. */
  23874. var SceneComponentConstants = /** @class */ (function () {
  23875. function SceneComponentConstants() {
  23876. }
  23877. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23878. SceneComponentConstants.NAME_LAYER = "Layer";
  23879. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23880. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23881. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23882. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23883. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23884. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23885. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23886. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23887. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23888. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23889. return SceneComponentConstants;
  23890. }());
  23891. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23892. /**
  23893. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23894. * @hidden
  23895. */
  23896. var Stage = /** @class */ (function (_super) {
  23897. __extends(Stage, _super);
  23898. /**
  23899. * Hide ctor from the rest of the world.
  23900. * @param items The items to add.
  23901. */
  23902. function Stage(items) {
  23903. return _super.apply(this, items) || this;
  23904. }
  23905. /**
  23906. * Creates a new Stage.
  23907. * @returns A new instance of a Stage
  23908. */
  23909. Stage.Create = function () {
  23910. return Object.create(Stage.prototype);
  23911. };
  23912. /**
  23913. * Registers a step in an ordered way in the targeted stage.
  23914. * @param index Defines the position to register the step in
  23915. * @param component Defines the component attached to the step
  23916. * @param action Defines the action to launch during the step
  23917. */
  23918. Stage.prototype.registerStep = function (index, component, action) {
  23919. var i = 0;
  23920. var maxIndex = Number.MAX_VALUE;
  23921. for (; i < this.length && i < maxIndex; i++) {
  23922. var step = this[i];
  23923. maxIndex = step.index;
  23924. }
  23925. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23926. };
  23927. /**
  23928. * Clears all the steps from the stage.
  23929. */
  23930. Stage.prototype.clear = function () {
  23931. this.length = 0;
  23932. };
  23933. return Stage;
  23934. }(Array));
  23935. BABYLON.Stage = Stage;
  23936. })(BABYLON || (BABYLON = {}));
  23937. //# sourceMappingURL=babylon.sceneComponent.js.map
  23938. var BABYLON;
  23939. (function (BABYLON) {
  23940. /**
  23941. * Base class of the scene acting as a container for the different elements composing a scene.
  23942. * This class is dynamically extended by the different components of the scene increasing
  23943. * flexibility and reducing coupling.
  23944. */
  23945. var AbstractScene = /** @class */ (function () {
  23946. function AbstractScene() {
  23947. /** All of the cameras added to this scene
  23948. * @see http://doc.babylonjs.com/babylon101/cameras
  23949. */
  23950. this.cameras = new Array();
  23951. /**
  23952. * All of the lights added to this scene
  23953. * @see http://doc.babylonjs.com/babylon101/lights
  23954. */
  23955. this.lights = new Array();
  23956. /**
  23957. * All of the (abstract) meshes added to this scene
  23958. */
  23959. this.meshes = new Array();
  23960. /**
  23961. * The list of skeletons added to the scene
  23962. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23963. */
  23964. this.skeletons = new Array();
  23965. /**
  23966. * All of the particle systems added to this scene
  23967. * @see http://doc.babylonjs.com/babylon101/particles
  23968. */
  23969. this.particleSystems = new Array();
  23970. /**
  23971. * Gets a list of Animations associated with the scene
  23972. */
  23973. this.animations = [];
  23974. /**
  23975. * All of the animation groups added to this scene
  23976. * @see http://doc.babylonjs.com/how_to/group
  23977. */
  23978. this.animationGroups = new Array();
  23979. /**
  23980. * All of the multi-materials added to this scene
  23981. * @see http://doc.babylonjs.com/how_to/multi_materials
  23982. */
  23983. this.multiMaterials = new Array();
  23984. /**
  23985. * All of the materials added to this scene
  23986. * @see http://doc.babylonjs.com/babylon101/materials
  23987. */
  23988. this.materials = new Array();
  23989. /**
  23990. * The list of morph target managers added to the scene
  23991. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23992. */
  23993. this.morphTargetManagers = new Array();
  23994. /**
  23995. * The list of geometries used in the scene.
  23996. */
  23997. this.geometries = new Array();
  23998. /**
  23999. * All of the tranform nodes added to this scene
  24000. * @see http://doc.babylonjs.com/how_to/transformnode
  24001. */
  24002. this.transformNodes = new Array();
  24003. /**
  24004. * ActionManagers available on the scene.
  24005. */
  24006. this.actionManagers = new Array();
  24007. /**
  24008. * Sounds to keep.
  24009. */
  24010. this.sounds = new Array();
  24011. /**
  24012. * Textures to keep.
  24013. */
  24014. this.textures = new Array();
  24015. }
  24016. /**
  24017. * Adds a parser in the list of availables ones.
  24018. * @param name Defines the name of the parser
  24019. * @param parser Defines the parser to add
  24020. */
  24021. AbstractScene.AddParser = function (name, parser) {
  24022. this._BabylonFileParsers[name] = parser;
  24023. };
  24024. /**
  24025. * Parser json data and populate both a scene and its associated container object
  24026. * @param jsonData Defines the data to parse
  24027. * @param scene Defines the scene to parse the data for
  24028. * @param container Defines the container attached to the parsing sequence
  24029. * @param rootUrl Defines the root url of the data
  24030. */
  24031. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24032. for (var parserName in this._BabylonFileParsers) {
  24033. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24034. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24035. }
  24036. }
  24037. };
  24038. /**
  24039. * Stores the list of available parsers in the application.
  24040. */
  24041. AbstractScene._BabylonFileParsers = {};
  24042. return AbstractScene;
  24043. }());
  24044. BABYLON.AbstractScene = AbstractScene;
  24045. })(BABYLON || (BABYLON = {}));
  24046. //# sourceMappingURL=babylon.abstractScene.js.map
  24047. var BABYLON;
  24048. (function (BABYLON) {
  24049. /** @hidden */
  24050. var ClickInfo = /** @class */ (function () {
  24051. function ClickInfo() {
  24052. this._singleClick = false;
  24053. this._doubleClick = false;
  24054. this._hasSwiped = false;
  24055. this._ignore = false;
  24056. }
  24057. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24058. get: function () {
  24059. return this._singleClick;
  24060. },
  24061. set: function (b) {
  24062. this._singleClick = b;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24068. get: function () {
  24069. return this._doubleClick;
  24070. },
  24071. set: function (b) {
  24072. this._doubleClick = b;
  24073. },
  24074. enumerable: true,
  24075. configurable: true
  24076. });
  24077. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24078. get: function () {
  24079. return this._hasSwiped;
  24080. },
  24081. set: function (b) {
  24082. this._hasSwiped = b;
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24088. get: function () {
  24089. return this._ignore;
  24090. },
  24091. set: function (b) {
  24092. this._ignore = b;
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. return ClickInfo;
  24098. }());
  24099. /**
  24100. * This class is used by the onRenderingGroupObservable
  24101. */
  24102. var RenderingGroupInfo = /** @class */ (function () {
  24103. function RenderingGroupInfo() {
  24104. }
  24105. /**
  24106. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24107. * This stage will be fired no matter what
  24108. */
  24109. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24110. /**
  24111. * Called before opaque object are rendered.
  24112. * This stage will be fired only if there's 3D Opaque content to render
  24113. */
  24114. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24115. /**
  24116. * Called after the opaque objects are rendered and before the transparent ones
  24117. * This stage will be fired only if there's 3D transparent content to render
  24118. */
  24119. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24120. /**
  24121. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24122. * This stage will be fired no matter what
  24123. */
  24124. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24125. return RenderingGroupInfo;
  24126. }());
  24127. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24128. /**
  24129. * Represents a scene to be rendered by the engine.
  24130. * @see http://doc.babylonjs.com/features/scene
  24131. */
  24132. var Scene = /** @class */ (function (_super) {
  24133. __extends(Scene, _super);
  24134. /**
  24135. * Creates a new Scene
  24136. * @param engine defines the engine to use to render this scene
  24137. */
  24138. function Scene(engine) {
  24139. var _this = _super.call(this) || this;
  24140. // Members
  24141. /**
  24142. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24143. */
  24144. _this.autoClear = true;
  24145. /**
  24146. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24147. */
  24148. _this.autoClearDepthAndStencil = true;
  24149. /**
  24150. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24151. */
  24152. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24153. /**
  24154. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24155. */
  24156. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24157. _this._forceWireframe = false;
  24158. _this._forcePointsCloud = false;
  24159. /**
  24160. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24161. */
  24162. _this.forceShowBoundingBoxes = false;
  24163. /**
  24164. * Gets or sets a boolean indicating if animations are enabled
  24165. */
  24166. _this.animationsEnabled = true;
  24167. _this._animationPropertiesOverride = null;
  24168. /**
  24169. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24170. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24171. */
  24172. _this.useConstantAnimationDeltaTime = false;
  24173. /**
  24174. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24175. * Please note that it requires to run a ray cast through the scene on every frame
  24176. */
  24177. _this.constantlyUpdateMeshUnderPointer = false;
  24178. /**
  24179. * Defines the HTML cursor to use when hovering over interactive elements
  24180. */
  24181. _this.hoverCursor = "pointer";
  24182. /**
  24183. * Defines the HTML default cursor to use (empty by default)
  24184. */
  24185. _this.defaultCursor = "";
  24186. /**
  24187. * This is used to call preventDefault() on pointer down
  24188. * in order to block unwanted artifacts like system double clicks
  24189. */
  24190. _this.preventDefaultOnPointerDown = true;
  24191. // Metadata
  24192. /**
  24193. * Gets or sets user defined metadata
  24194. */
  24195. _this.metadata = null;
  24196. /**
  24197. * Use this array to add regular expressions used to disable offline support for specific urls
  24198. */
  24199. _this.disableOfflineSupportExceptionRules = new Array();
  24200. /**
  24201. * An event triggered when the scene is disposed.
  24202. */
  24203. _this.onDisposeObservable = new BABYLON.Observable();
  24204. _this._onDisposeObserver = null;
  24205. /**
  24206. * An event triggered before rendering the scene (right after animations and physics)
  24207. */
  24208. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24209. _this._onBeforeRenderObserver = null;
  24210. /**
  24211. * An event triggered after rendering the scene
  24212. */
  24213. _this.onAfterRenderObservable = new BABYLON.Observable();
  24214. _this._onAfterRenderObserver = null;
  24215. /**
  24216. * An event triggered before animating the scene
  24217. */
  24218. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24219. /**
  24220. * An event triggered after animations processing
  24221. */
  24222. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24223. /**
  24224. * An event triggered before draw calls are ready to be sent
  24225. */
  24226. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24227. /**
  24228. * An event triggered after draw calls have been sent
  24229. */
  24230. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24231. /**
  24232. * An event triggered when physic simulation is about to be run
  24233. */
  24234. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24235. /**
  24236. * An event triggered when physic simulation has been done
  24237. */
  24238. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24239. /**
  24240. * An event triggered when the scene is ready
  24241. */
  24242. _this.onReadyObservable = new BABYLON.Observable();
  24243. /**
  24244. * An event triggered before rendering a camera
  24245. */
  24246. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24247. _this._onBeforeCameraRenderObserver = null;
  24248. /**
  24249. * An event triggered after rendering a camera
  24250. */
  24251. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24252. _this._onAfterCameraRenderObserver = null;
  24253. /**
  24254. * An event triggered when active meshes evaluation is about to start
  24255. */
  24256. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24257. /**
  24258. * An event triggered when active meshes evaluation is done
  24259. */
  24260. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24261. /**
  24262. * An event triggered when particles rendering is about to start
  24263. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24264. */
  24265. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24266. /**
  24267. * An event triggered when particles rendering is done
  24268. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24269. */
  24270. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24271. /**
  24272. * An event triggered when sprites rendering is about to start
  24273. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24274. */
  24275. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24276. /**
  24277. * An event triggered when sprites rendering is done
  24278. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24279. */
  24280. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24281. /**
  24282. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24283. */
  24284. _this.onDataLoadedObservable = new BABYLON.Observable();
  24285. /**
  24286. * An event triggered when a camera is created
  24287. */
  24288. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24289. /**
  24290. * An event triggered when a camera is removed
  24291. */
  24292. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24293. /**
  24294. * An event triggered when a light is created
  24295. */
  24296. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24297. /**
  24298. * An event triggered when a light is removed
  24299. */
  24300. _this.onLightRemovedObservable = new BABYLON.Observable();
  24301. /**
  24302. * An event triggered when a geometry is created
  24303. */
  24304. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24305. /**
  24306. * An event triggered when a geometry is removed
  24307. */
  24308. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24309. /**
  24310. * An event triggered when a transform node is created
  24311. */
  24312. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24313. /**
  24314. * An event triggered when a transform node is removed
  24315. */
  24316. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24317. /**
  24318. * An event triggered when a mesh is created
  24319. */
  24320. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24321. /**
  24322. * An event triggered when a mesh is removed
  24323. */
  24324. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24325. /**
  24326. * An event triggered when render targets are about to be rendered
  24327. * Can happen multiple times per frame.
  24328. */
  24329. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24330. /**
  24331. * An event triggered when render targets were rendered.
  24332. * Can happen multiple times per frame.
  24333. */
  24334. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24335. /**
  24336. * An event triggered before calculating deterministic simulation step
  24337. */
  24338. _this.onBeforeStepObservable = new BABYLON.Observable();
  24339. /**
  24340. * An event triggered after calculating deterministic simulation step
  24341. */
  24342. _this.onAfterStepObservable = new BABYLON.Observable();
  24343. /**
  24344. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24345. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24346. * 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)
  24347. */
  24348. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24349. // Animations
  24350. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24351. /**
  24352. * 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).
  24353. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24354. */
  24355. _this.onPrePointerObservable = new BABYLON.Observable();
  24356. /**
  24357. * Observable event triggered each time an input event is received from the rendering canvas
  24358. */
  24359. _this.onPointerObservable = new BABYLON.Observable();
  24360. _this._meshPickProceed = false;
  24361. _this._currentPickResult = null;
  24362. _this._previousPickResult = null;
  24363. _this._totalPointersPressed = 0;
  24364. _this._doubleClickOccured = false;
  24365. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24366. _this.cameraToUseForPointers = null;
  24367. _this._pointerX = 0;
  24368. _this._pointerY = 0;
  24369. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24370. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24371. _this._startingPointerTime = 0;
  24372. _this._previousStartingPointerTime = 0;
  24373. _this._pointerCaptures = {};
  24374. // Deterministic lockstep
  24375. _this._timeAccumulator = 0;
  24376. _this._currentStepId = 0;
  24377. _this._currentInternalStep = 0;
  24378. // Keyboard
  24379. /**
  24380. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24381. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24382. */
  24383. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24384. /**
  24385. * Observable event triggered each time an keyboard event is received from the hosting window
  24386. */
  24387. _this.onKeyboardObservable = new BABYLON.Observable();
  24388. // Coordinates system
  24389. _this._useRightHandedSystem = false;
  24390. // Fog
  24391. _this._fogEnabled = true;
  24392. _this._fogMode = Scene.FOGMODE_NONE;
  24393. /**
  24394. * Gets or sets the fog color to use
  24395. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24396. */
  24397. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24398. /**
  24399. * Gets or sets the fog density to use
  24400. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24401. */
  24402. _this.fogDensity = 0.1;
  24403. /**
  24404. * Gets or sets the fog start distance to use
  24405. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24406. */
  24407. _this.fogStart = 0;
  24408. /**
  24409. * Gets or sets the fog end distance to use
  24410. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24411. */
  24412. _this.fogEnd = 1000.0;
  24413. // Lights
  24414. _this._shadowsEnabled = true;
  24415. _this._lightsEnabled = true;
  24416. /** All of the active cameras added to this scene. */
  24417. _this.activeCameras = new Array();
  24418. // Textures
  24419. _this._texturesEnabled = true;
  24420. // Particles
  24421. /**
  24422. * Gets or sets a boolean indicating if particles are enabled on this scene
  24423. */
  24424. _this.particlesEnabled = true;
  24425. // Sprites
  24426. /**
  24427. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24428. */
  24429. _this.spritesEnabled = true;
  24430. /**
  24431. * All of the sprite managers added to this scene
  24432. * @see http://doc.babylonjs.com/babylon101/sprites
  24433. */
  24434. _this.spriteManagers = new Array();
  24435. // Skeletons
  24436. _this._skeletonsEnabled = true;
  24437. // Lens flares
  24438. /**
  24439. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24440. */
  24441. _this.lensFlaresEnabled = true;
  24442. // Collisions
  24443. /**
  24444. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24445. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24446. */
  24447. _this.collisionsEnabled = true;
  24448. /**
  24449. * Defines the gravity applied to this scene (used only for collisions)
  24450. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24451. */
  24452. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24453. // Postprocesses
  24454. /**
  24455. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24456. */
  24457. _this.postProcessesEnabled = true;
  24458. /**
  24459. * The list of postprocesses added to the scene
  24460. */
  24461. _this.postProcesses = new Array();
  24462. // Customs render targets
  24463. /**
  24464. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24465. */
  24466. _this.renderTargetsEnabled = true;
  24467. /**
  24468. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24469. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24470. */
  24471. _this.dumpNextRenderTargets = false;
  24472. /**
  24473. * The list of user defined render targets added to the scene
  24474. */
  24475. _this.customRenderTargets = new Array();
  24476. /**
  24477. * Gets the list of meshes imported to the scene through SceneLoader
  24478. */
  24479. _this.importedMeshesFiles = new Array();
  24480. // Probes
  24481. /**
  24482. * Gets or sets a boolean indicating if probes are enabled on this scene
  24483. */
  24484. _this.probesEnabled = true;
  24485. /**
  24486. * The list of reflection probes added to the scene
  24487. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24488. */
  24489. _this.reflectionProbes = new Array();
  24490. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24491. // Procedural textures
  24492. /**
  24493. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24494. */
  24495. _this.proceduralTexturesEnabled = true;
  24496. /**
  24497. * The list of procedural textures added to the scene
  24498. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24499. */
  24500. _this.proceduralTextures = new Array();
  24501. /**
  24502. * The list of sound tracks added to the scene
  24503. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24504. */
  24505. _this.soundTracks = new Array();
  24506. _this._audioEnabled = true;
  24507. _this._headphone = false;
  24508. // Performance counters
  24509. _this._totalVertices = new BABYLON.PerfCounter();
  24510. /** @hidden */
  24511. _this._activeIndices = new BABYLON.PerfCounter();
  24512. /** @hidden */
  24513. _this._activeParticles = new BABYLON.PerfCounter();
  24514. /** @hidden */
  24515. _this._activeBones = new BABYLON.PerfCounter();
  24516. _this._animationTime = 0;
  24517. /**
  24518. * Gets or sets a general scale for animation speed
  24519. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24520. */
  24521. _this.animationTimeScale = 1;
  24522. _this._renderId = 0;
  24523. _this._executeWhenReadyTimeoutId = -1;
  24524. _this._intermediateRendering = false;
  24525. _this._viewUpdateFlag = -1;
  24526. _this._projectionUpdateFlag = -1;
  24527. _this._alternateViewUpdateFlag = -1;
  24528. _this._alternateProjectionUpdateFlag = -1;
  24529. /** @hidden */
  24530. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24531. _this._activeRequests = new Array();
  24532. _this._pendingData = new Array();
  24533. _this._isDisposed = false;
  24534. /**
  24535. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24536. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24537. */
  24538. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24539. _this._activeMeshes = new BABYLON.SmartArray(256);
  24540. _this._processedMaterials = new BABYLON.SmartArray(256);
  24541. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24542. /** @hidden */
  24543. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24544. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24545. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24546. /** @hidden */
  24547. _this._activeAnimatables = new Array();
  24548. _this._transformMatrix = BABYLON.Matrix.Zero();
  24549. _this._useAlternateCameraConfiguration = false;
  24550. _this._alternateRendering = false;
  24551. /**
  24552. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24553. * This is useful if there are more lights that the maximum simulteanous authorized
  24554. */
  24555. _this.requireLightSorting = false;
  24556. _this._depthRenderer = {};
  24557. /**
  24558. * Backing store of defined scene components.
  24559. */
  24560. _this._components = [];
  24561. /**
  24562. * List of components to register on the next registration step.
  24563. */
  24564. _this._transientComponents = [];
  24565. /**
  24566. * Defines the actions happening during the per mesh ready checks.
  24567. */
  24568. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24569. /**
  24570. * Defines the actions happening during the per camera render target step.
  24571. */
  24572. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24573. /**
  24574. * Defines the actions happening just before the active camera is drawing.
  24575. */
  24576. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24577. /**
  24578. * Defines the actions happening just before a rendering group is drawing.
  24579. */
  24580. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24581. /**
  24582. * Defines the actions happening just after a rendering group has been drawn.
  24583. */
  24584. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24585. /**
  24586. * Defines the actions happening just after the active camera has been drawn.
  24587. */
  24588. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24589. _this._activeMeshesFrozen = false;
  24590. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24591. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24592. _this._engine.scenes.push(_this);
  24593. _this._uid = null;
  24594. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24595. if (BABYLON.PostProcessManager) {
  24596. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24597. }
  24598. if (BABYLON.OutlineRenderer) {
  24599. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24600. }
  24601. if (BABYLON.Tools.IsWindowObjectExist()) {
  24602. _this.attachControl();
  24603. }
  24604. //simplification queue
  24605. if (BABYLON.SimplificationQueue) {
  24606. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24607. }
  24608. //collision coordinator initialization. For now legacy per default.
  24609. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24610. // Uniform Buffer
  24611. _this._createUbo();
  24612. // Default Image processing definition
  24613. if (BABYLON.ImageProcessingConfiguration) {
  24614. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24615. }
  24616. return _this;
  24617. }
  24618. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24619. /** The fog is deactivated */
  24620. get: function () {
  24621. return Scene._FOGMODE_NONE;
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24627. /** The fog density is following an exponential function */
  24628. get: function () {
  24629. return Scene._FOGMODE_EXP;
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24635. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24636. get: function () {
  24637. return Scene._FOGMODE_EXP2;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24643. /** The fog density is following a linear function. */
  24644. get: function () {
  24645. return Scene._FOGMODE_LINEAR;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24651. /**
  24652. * Texture used in all pbr material as the reflection texture.
  24653. * As in the majority of the scene they are the same (exception for multi room and so on),
  24654. * this is easier to reference from here than from all the materials.
  24655. */
  24656. get: function () {
  24657. return this._environmentTexture;
  24658. },
  24659. /**
  24660. * Texture used in all pbr material as the reflection texture.
  24661. * As in the majority of the scene they are the same (exception for multi room and so on),
  24662. * this is easier to set here than in all the materials.
  24663. */
  24664. set: function (value) {
  24665. if (this._environmentTexture === value) {
  24666. return;
  24667. }
  24668. this._environmentTexture = value;
  24669. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24675. /**
  24676. * Default image processing configuration used either in the rendering
  24677. * Forward main pass or through the imageProcessingPostProcess if present.
  24678. * As in the majority of the scene they are the same (exception for multi camera),
  24679. * this is easier to reference from here than from all the materials and post process.
  24680. *
  24681. * No setter as we it is a shared configuration, you can set the values instead.
  24682. */
  24683. get: function () {
  24684. return this._imageProcessingConfiguration;
  24685. },
  24686. enumerable: true,
  24687. configurable: true
  24688. });
  24689. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24690. get: function () {
  24691. return this._forceWireframe;
  24692. },
  24693. /**
  24694. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24695. */
  24696. set: function (value) {
  24697. if (this._forceWireframe === value) {
  24698. return;
  24699. }
  24700. this._forceWireframe = value;
  24701. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24707. get: function () {
  24708. return this._forcePointsCloud;
  24709. },
  24710. /**
  24711. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24712. */
  24713. set: function (value) {
  24714. if (this._forcePointsCloud === value) {
  24715. return;
  24716. }
  24717. this._forcePointsCloud = value;
  24718. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24724. /**
  24725. * Gets or sets the animation properties override
  24726. */
  24727. get: function () {
  24728. return this._animationPropertiesOverride;
  24729. },
  24730. set: function (value) {
  24731. this._animationPropertiesOverride = value;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. Object.defineProperty(Scene.prototype, "onDispose", {
  24737. /** Sets a function to be executed when this scene is disposed. */
  24738. set: function (callback) {
  24739. if (this._onDisposeObserver) {
  24740. this.onDisposeObservable.remove(this._onDisposeObserver);
  24741. }
  24742. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24743. },
  24744. enumerable: true,
  24745. configurable: true
  24746. });
  24747. Object.defineProperty(Scene.prototype, "beforeRender", {
  24748. /** Sets a function to be executed before rendering this scene */
  24749. set: function (callback) {
  24750. if (this._onBeforeRenderObserver) {
  24751. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24752. }
  24753. if (callback) {
  24754. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24755. }
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "afterRender", {
  24761. /** Sets a function to be executed after rendering this scene */
  24762. set: function (callback) {
  24763. if (this._onAfterRenderObserver) {
  24764. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24765. }
  24766. if (callback) {
  24767. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24768. }
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24774. /** Sets a function to be executed before rendering a camera*/
  24775. set: function (callback) {
  24776. if (this._onBeforeCameraRenderObserver) {
  24777. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24778. }
  24779. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24785. /** Sets a function to be executed after rendering a camera*/
  24786. set: function (callback) {
  24787. if (this._onAfterCameraRenderObserver) {
  24788. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24789. }
  24790. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24791. },
  24792. enumerable: true,
  24793. configurable: true
  24794. });
  24795. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24796. /**
  24797. * Gets the gamepad manager associated with the scene
  24798. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24799. */
  24800. get: function () {
  24801. if (!this._gamepadManager) {
  24802. this._gamepadManager = new BABYLON.GamepadManager(this);
  24803. }
  24804. return this._gamepadManager;
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24810. /**
  24811. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24812. */
  24813. get: function () {
  24814. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24820. get: function () {
  24821. return this._useRightHandedSystem;
  24822. },
  24823. /**
  24824. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24825. */
  24826. set: function (value) {
  24827. if (this._useRightHandedSystem === value) {
  24828. return;
  24829. }
  24830. this._useRightHandedSystem = value;
  24831. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24832. },
  24833. enumerable: true,
  24834. configurable: true
  24835. });
  24836. /**
  24837. * Sets the step Id used by deterministic lock step
  24838. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24839. * @param newStepId defines the step Id
  24840. */
  24841. Scene.prototype.setStepId = function (newStepId) {
  24842. this._currentStepId = newStepId;
  24843. };
  24844. ;
  24845. /**
  24846. * Gets the step Id used by deterministic lock step
  24847. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24848. * @returns the step Id
  24849. */
  24850. Scene.prototype.getStepId = function () {
  24851. return this._currentStepId;
  24852. };
  24853. ;
  24854. /**
  24855. * Gets the internal step used by deterministic lock step
  24856. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24857. * @returns the internal step
  24858. */
  24859. Scene.prototype.getInternalStep = function () {
  24860. return this._currentInternalStep;
  24861. };
  24862. ;
  24863. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24864. get: function () {
  24865. return this._fogEnabled;
  24866. },
  24867. /**
  24868. * Gets or sets a boolean indicating if fog is enabled on this scene
  24869. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24870. */
  24871. set: function (value) {
  24872. if (this._fogEnabled === value) {
  24873. return;
  24874. }
  24875. this._fogEnabled = value;
  24876. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(Scene.prototype, "fogMode", {
  24882. get: function () {
  24883. return this._fogMode;
  24884. },
  24885. /**
  24886. * Gets or sets the fog mode to use
  24887. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24888. */
  24889. set: function (value) {
  24890. if (this._fogMode === value) {
  24891. return;
  24892. }
  24893. this._fogMode = value;
  24894. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24900. get: function () {
  24901. return this._shadowsEnabled;
  24902. },
  24903. /**
  24904. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24905. */
  24906. set: function (value) {
  24907. if (this._shadowsEnabled === value) {
  24908. return;
  24909. }
  24910. this._shadowsEnabled = value;
  24911. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24917. get: function () {
  24918. return this._lightsEnabled;
  24919. },
  24920. /**
  24921. * Gets or sets a boolean indicating if lights are enabled on this scene
  24922. */
  24923. set: function (value) {
  24924. if (this._lightsEnabled === value) {
  24925. return;
  24926. }
  24927. this._lightsEnabled = value;
  24928. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24929. },
  24930. enumerable: true,
  24931. configurable: true
  24932. });
  24933. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24934. /** The default material used on meshes when no material is affected */
  24935. get: function () {
  24936. if (!this._defaultMaterial) {
  24937. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24938. }
  24939. return this._defaultMaterial;
  24940. },
  24941. /** The default material used on meshes when no material is affected */
  24942. set: function (value) {
  24943. this._defaultMaterial = value;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24949. get: function () {
  24950. return this._texturesEnabled;
  24951. },
  24952. /**
  24953. * Gets or sets a boolean indicating if textures are enabled on this scene
  24954. */
  24955. set: function (value) {
  24956. if (this._texturesEnabled === value) {
  24957. return;
  24958. }
  24959. this._texturesEnabled = value;
  24960. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24966. get: function () {
  24967. return this._skeletonsEnabled;
  24968. },
  24969. /**
  24970. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24971. */
  24972. set: function (value) {
  24973. if (this._skeletonsEnabled === value) {
  24974. return;
  24975. }
  24976. this._skeletonsEnabled = value;
  24977. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24978. },
  24979. enumerable: true,
  24980. configurable: true
  24981. });
  24982. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24983. /**
  24984. * Gets the postprocess render pipeline manager
  24985. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24986. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24987. */
  24988. get: function () {
  24989. if (!this._postProcessRenderPipelineManager) {
  24990. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24991. }
  24992. return this._postProcessRenderPipelineManager;
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24998. /**
  24999. * Gets the main soundtrack associated with the scene
  25000. */
  25001. get: function () {
  25002. if (!this._mainSoundTrack) {
  25003. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  25004. }
  25005. return this._mainSoundTrack;
  25006. },
  25007. enumerable: true,
  25008. configurable: true
  25009. });
  25010. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25011. /** @hidden */
  25012. get: function () {
  25013. return this._alternateRendering;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25019. /**
  25020. * Gets the list of frustum planes (built from the active camera)
  25021. */
  25022. get: function () {
  25023. return this._frustumPlanes;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  25029. /**
  25030. * Gets the current geometry buffer associated to the scene.
  25031. */
  25032. get: function () {
  25033. return this._geometryBufferRenderer;
  25034. },
  25035. /**
  25036. * Sets the current geometry buffer for the scene.
  25037. */
  25038. set: function (geometryBufferRenderer) {
  25039. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  25040. this._geometryBufferRenderer = geometryBufferRenderer;
  25041. }
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. /**
  25047. * Registers the transient components if needed.
  25048. */
  25049. Scene.prototype._registerTransientComponents = function () {
  25050. // Register components that have been associated lately to the scene.
  25051. if (this._transientComponents.length > 0) {
  25052. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25053. var component = _a[_i];
  25054. component.register();
  25055. }
  25056. this._transientComponents = [];
  25057. }
  25058. };
  25059. /**
  25060. * Add a component to the scene.
  25061. * Note that the ccomponent could be registered on th next frame if this is called after
  25062. * the register component stage.
  25063. * @param component Defines the component to add to the scene
  25064. */
  25065. Scene.prototype._addComponent = function (component) {
  25066. this._components.push(component);
  25067. this._transientComponents.push(component);
  25068. };
  25069. /**
  25070. * Gets a component from the scene.
  25071. * @param name defines the name of the component to retrieve
  25072. * @returns the component or null if not present
  25073. */
  25074. Scene.prototype._getComponent = function (name) {
  25075. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25076. var component = _a[_i];
  25077. if (component.name === name) {
  25078. return component;
  25079. }
  25080. }
  25081. return null;
  25082. };
  25083. Object.defineProperty(Scene.prototype, "debugLayer", {
  25084. /**
  25085. * Gets the debug layer (aka Inspector) associated with the scene
  25086. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25087. */
  25088. get: function () {
  25089. if (!this._debugLayer) {
  25090. this._debugLayer = new BABYLON.DebugLayer(this);
  25091. }
  25092. return this._debugLayer;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25098. /**
  25099. * Gets a boolean indicating if collisions are processed on a web worker
  25100. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25101. */
  25102. get: function () {
  25103. return this._workerCollisions;
  25104. },
  25105. set: function (enabled) {
  25106. if (!BABYLON.CollisionCoordinatorLegacy) {
  25107. return;
  25108. }
  25109. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25110. this._workerCollisions = enabled;
  25111. if (this.collisionCoordinator) {
  25112. this.collisionCoordinator.destroy();
  25113. }
  25114. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25115. this.collisionCoordinator.init(this);
  25116. },
  25117. enumerable: true,
  25118. configurable: true
  25119. });
  25120. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25121. /**
  25122. * Gets the octree used to boost mesh selection (picking)
  25123. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25124. */
  25125. get: function () {
  25126. return this._selectionOctree;
  25127. },
  25128. enumerable: true,
  25129. configurable: true
  25130. });
  25131. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25132. /**
  25133. * Gets the mesh that is currently under the pointer
  25134. */
  25135. get: function () {
  25136. return this._pointerOverMesh;
  25137. },
  25138. enumerable: true,
  25139. configurable: true
  25140. });
  25141. Object.defineProperty(Scene.prototype, "pointerX", {
  25142. /**
  25143. * Gets the current on-screen X position of the pointer
  25144. */
  25145. get: function () {
  25146. return this._pointerX;
  25147. },
  25148. enumerable: true,
  25149. configurable: true
  25150. });
  25151. Object.defineProperty(Scene.prototype, "pointerY", {
  25152. /**
  25153. * Gets the current on-screen Y position of the pointer
  25154. */
  25155. get: function () {
  25156. return this._pointerY;
  25157. },
  25158. enumerable: true,
  25159. configurable: true
  25160. });
  25161. /**
  25162. * Gets the cached material (ie. the latest rendered one)
  25163. * @returns the cached material
  25164. */
  25165. Scene.prototype.getCachedMaterial = function () {
  25166. return this._cachedMaterial;
  25167. };
  25168. /**
  25169. * Gets the cached effect (ie. the latest rendered one)
  25170. * @returns the cached effect
  25171. */
  25172. Scene.prototype.getCachedEffect = function () {
  25173. return this._cachedEffect;
  25174. };
  25175. /**
  25176. * Gets the cached visibility state (ie. the latest rendered one)
  25177. * @returns the cached visibility state
  25178. */
  25179. Scene.prototype.getCachedVisibility = function () {
  25180. return this._cachedVisibility;
  25181. };
  25182. /**
  25183. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25184. * @param material defines the current material
  25185. * @param effect defines the current effect
  25186. * @param visibility defines the current visibility state
  25187. * @returns true if one parameter is not cached
  25188. */
  25189. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25190. if (visibility === void 0) { visibility = 1; }
  25191. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25192. };
  25193. /**
  25194. * Gets the bounding box renderer associated with the scene
  25195. * @returns a BoundingBoxRenderer
  25196. */
  25197. Scene.prototype.getBoundingBoxRenderer = function () {
  25198. if (!this._boundingBoxRenderer) {
  25199. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25200. }
  25201. return this._boundingBoxRenderer;
  25202. };
  25203. /**
  25204. * Gets the outline renderer associated with the scene
  25205. * @returns a OutlineRenderer
  25206. */
  25207. Scene.prototype.getOutlineRenderer = function () {
  25208. return this._outlineRenderer;
  25209. };
  25210. /**
  25211. * Gets the engine associated with the scene
  25212. * @returns an Engine
  25213. */
  25214. Scene.prototype.getEngine = function () {
  25215. return this._engine;
  25216. };
  25217. /**
  25218. * Gets the total number of vertices rendered per frame
  25219. * @returns the total number of vertices rendered per frame
  25220. */
  25221. Scene.prototype.getTotalVertices = function () {
  25222. return this._totalVertices.current;
  25223. };
  25224. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25225. /**
  25226. * Gets the performance counter for total vertices
  25227. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25228. */
  25229. get: function () {
  25230. return this._totalVertices;
  25231. },
  25232. enumerable: true,
  25233. configurable: true
  25234. });
  25235. /**
  25236. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25237. * @returns the total number of active indices rendered per frame
  25238. */
  25239. Scene.prototype.getActiveIndices = function () {
  25240. return this._activeIndices.current;
  25241. };
  25242. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25243. /**
  25244. * Gets the performance counter for active indices
  25245. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25246. */
  25247. get: function () {
  25248. return this._activeIndices;
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. /**
  25254. * Gets the total number of active particles rendered per frame
  25255. * @returns the total number of active particles rendered per frame
  25256. */
  25257. Scene.prototype.getActiveParticles = function () {
  25258. return this._activeParticles.current;
  25259. };
  25260. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25261. /**
  25262. * Gets the performance counter for active particles
  25263. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25264. */
  25265. get: function () {
  25266. return this._activeParticles;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. /**
  25272. * Gets the total number of active bones rendered per frame
  25273. * @returns the total number of active bones rendered per frame
  25274. */
  25275. Scene.prototype.getActiveBones = function () {
  25276. return this._activeBones.current;
  25277. };
  25278. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25279. /**
  25280. * Gets the performance counter for active bones
  25281. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25282. */
  25283. get: function () {
  25284. return this._activeBones;
  25285. },
  25286. enumerable: true,
  25287. configurable: true
  25288. });
  25289. /** @hidden */
  25290. Scene.prototype.getInterFramePerfCounter = function () {
  25291. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25292. return 0;
  25293. };
  25294. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25295. /** @hidden */
  25296. get: function () {
  25297. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25298. return null;
  25299. },
  25300. enumerable: true,
  25301. configurable: true
  25302. });
  25303. /** @hidden */
  25304. Scene.prototype.getLastFrameDuration = function () {
  25305. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25306. return 0;
  25307. };
  25308. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25309. /** @hidden */
  25310. get: function () {
  25311. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25312. return null;
  25313. },
  25314. enumerable: true,
  25315. configurable: true
  25316. });
  25317. /** @hidden */
  25318. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25319. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25320. return 0;
  25321. };
  25322. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25323. /** @hidden */
  25324. get: function () {
  25325. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25326. return null;
  25327. },
  25328. enumerable: true,
  25329. configurable: true
  25330. });
  25331. /**
  25332. * Gets the array of active meshes
  25333. * @returns an array of AbstractMesh
  25334. */
  25335. Scene.prototype.getActiveMeshes = function () {
  25336. return this._activeMeshes;
  25337. };
  25338. /** @hidden */
  25339. Scene.prototype.getRenderTargetsDuration = function () {
  25340. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25341. return 0;
  25342. };
  25343. /** @hidden */
  25344. Scene.prototype.getRenderDuration = function () {
  25345. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25346. return 0;
  25347. };
  25348. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25349. /** @hidden */
  25350. get: function () {
  25351. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25352. return null;
  25353. },
  25354. enumerable: true,
  25355. configurable: true
  25356. });
  25357. /** @hidden */
  25358. Scene.prototype.getParticlesDuration = function () {
  25359. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25360. return 0;
  25361. };
  25362. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25363. /** @hidden */
  25364. get: function () {
  25365. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25366. return null;
  25367. },
  25368. enumerable: true,
  25369. configurable: true
  25370. });
  25371. /** @hidden */
  25372. Scene.prototype.getSpritesDuration = function () {
  25373. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25374. return 0;
  25375. };
  25376. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25377. /** @hidden */
  25378. get: function () {
  25379. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25380. return null;
  25381. },
  25382. enumerable: true,
  25383. configurable: true
  25384. });
  25385. /**
  25386. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25387. * @returns a number
  25388. */
  25389. Scene.prototype.getAnimationRatio = function () {
  25390. return this._animationRatio;
  25391. };
  25392. /**
  25393. * Gets an unique Id for the current frame
  25394. * @returns a number
  25395. */
  25396. Scene.prototype.getRenderId = function () {
  25397. return this._renderId;
  25398. };
  25399. /** Call this function if you want to manually increment the render Id*/
  25400. Scene.prototype.incrementRenderId = function () {
  25401. this._renderId++;
  25402. };
  25403. Scene.prototype._updatePointerPosition = function (evt) {
  25404. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25405. if (!canvasRect) {
  25406. return;
  25407. }
  25408. this._pointerX = evt.clientX - canvasRect.left;
  25409. this._pointerY = evt.clientY - canvasRect.top;
  25410. this._unTranslatedPointerX = this._pointerX;
  25411. this._unTranslatedPointerY = this._pointerY;
  25412. };
  25413. Scene.prototype._createUbo = function () {
  25414. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25415. this._sceneUbo.addUniform("viewProjection", 16);
  25416. this._sceneUbo.addUniform("view", 16);
  25417. };
  25418. Scene.prototype._createAlternateUbo = function () {
  25419. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25420. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25421. this._alternateSceneUbo.addUniform("view", 16);
  25422. };
  25423. // Pointers handling
  25424. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25425. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25426. if (result) {
  25427. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25428. }
  25429. return result;
  25430. };
  25431. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25432. if (pointerInfo.pickInfo) {
  25433. if (!pointerInfo.pickInfo.ray) {
  25434. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25435. }
  25436. }
  25437. };
  25438. /**
  25439. * Use this method to simulate a pointer move on a mesh
  25440. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25441. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25442. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25443. * @returns the current scene
  25444. */
  25445. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25446. var evt = new PointerEvent("pointermove", pointerEventInit);
  25447. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25448. return this;
  25449. }
  25450. return this._processPointerMove(pickResult, evt);
  25451. };
  25452. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25453. var canvas = this._engine.getRenderingCanvas();
  25454. if (!canvas) {
  25455. return this;
  25456. }
  25457. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25458. this.setPointerOverSprite(null);
  25459. this.setPointerOverMesh(pickResult.pickedMesh);
  25460. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25461. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25462. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25463. }
  25464. else {
  25465. canvas.style.cursor = this.hoverCursor;
  25466. }
  25467. }
  25468. else {
  25469. canvas.style.cursor = this.defaultCursor;
  25470. }
  25471. }
  25472. else {
  25473. this.setPointerOverMesh(null);
  25474. // Sprites
  25475. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25476. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25477. this.setPointerOverSprite(pickResult.pickedSprite);
  25478. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25479. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25480. }
  25481. else {
  25482. canvas.style.cursor = this.hoverCursor;
  25483. }
  25484. }
  25485. else {
  25486. this.setPointerOverSprite(null);
  25487. // Restore pointer
  25488. canvas.style.cursor = this.defaultCursor;
  25489. }
  25490. }
  25491. if (pickResult) {
  25492. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25493. if (this.onPointerMove) {
  25494. this.onPointerMove(evt, pickResult, type);
  25495. }
  25496. if (this.onPointerObservable.hasObservers()) {
  25497. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25498. this._setRayOnPointerInfo(pi);
  25499. this.onPointerObservable.notifyObservers(pi, type);
  25500. }
  25501. }
  25502. return this;
  25503. };
  25504. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25505. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25506. if (pickResult) {
  25507. pi.ray = pickResult.ray;
  25508. }
  25509. this.onPrePointerObservable.notifyObservers(pi, type);
  25510. if (pi.skipOnPointerObservable) {
  25511. return true;
  25512. }
  25513. else {
  25514. return false;
  25515. }
  25516. };
  25517. /**
  25518. * Use this method to simulate a pointer down on a mesh
  25519. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25520. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25521. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25522. * @returns the current scene
  25523. */
  25524. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25525. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25526. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25527. return this;
  25528. }
  25529. return this._processPointerDown(pickResult, evt);
  25530. };
  25531. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25532. var _this = this;
  25533. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25534. this._pickedDownMesh = pickResult.pickedMesh;
  25535. var actionManager = pickResult.pickedMesh.actionManager;
  25536. if (actionManager) {
  25537. if (actionManager.hasPickTriggers) {
  25538. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25539. switch (evt.button) {
  25540. case 0:
  25541. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25542. break;
  25543. case 1:
  25544. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25545. break;
  25546. case 2:
  25547. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25548. break;
  25549. }
  25550. }
  25551. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25552. window.setTimeout(function () {
  25553. 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);
  25554. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25555. if (_this._totalPointersPressed !== 0 &&
  25556. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25557. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25558. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25559. _this._startingPointerTime = 0;
  25560. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25561. }
  25562. }
  25563. }, Scene.LongPressDelay);
  25564. }
  25565. }
  25566. }
  25567. if (pickResult) {
  25568. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25569. if (this.onPointerDown) {
  25570. this.onPointerDown(evt, pickResult, type);
  25571. }
  25572. if (this.onPointerObservable.hasObservers()) {
  25573. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25574. this._setRayOnPointerInfo(pi);
  25575. this.onPointerObservable.notifyObservers(pi, type);
  25576. }
  25577. }
  25578. return this;
  25579. };
  25580. /**
  25581. * Use this method to simulate a pointer up on a mesh
  25582. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25583. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25584. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25585. * @returns the current scene
  25586. */
  25587. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25588. var evt = new PointerEvent("pointerup", pointerEventInit);
  25589. var clickInfo = new ClickInfo();
  25590. clickInfo.singleClick = true;
  25591. clickInfo.ignore = true;
  25592. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25593. return this;
  25594. }
  25595. return this._processPointerUp(pickResult, evt, clickInfo);
  25596. };
  25597. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25598. if (pickResult && pickResult && pickResult.pickedMesh) {
  25599. this._pickedUpMesh = pickResult.pickedMesh;
  25600. if (this._pickedDownMesh === this._pickedUpMesh) {
  25601. if (this.onPointerPick) {
  25602. this.onPointerPick(evt, pickResult);
  25603. }
  25604. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25605. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25606. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25607. this._setRayOnPointerInfo(pi);
  25608. this.onPointerObservable.notifyObservers(pi, type_1);
  25609. }
  25610. }
  25611. if (pickResult.pickedMesh.actionManager) {
  25612. if (clickInfo.ignore) {
  25613. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25614. }
  25615. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25616. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25617. }
  25618. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25619. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25620. }
  25621. }
  25622. }
  25623. if (this._pickedDownMesh &&
  25624. this._pickedDownMesh.actionManager &&
  25625. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25626. this._pickedDownMesh !== this._pickedUpMesh) {
  25627. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25628. }
  25629. var type = BABYLON.PointerEventTypes.POINTERUP;
  25630. if (this.onPointerObservable.hasObservers()) {
  25631. if (!clickInfo.ignore) {
  25632. if (!clickInfo.hasSwiped) {
  25633. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25634. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25635. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25636. this._setRayOnPointerInfo(pi);
  25637. this.onPointerObservable.notifyObservers(pi, type_2);
  25638. }
  25639. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25640. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25641. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25642. this._setRayOnPointerInfo(pi);
  25643. this.onPointerObservable.notifyObservers(pi, type_3);
  25644. }
  25645. }
  25646. }
  25647. else {
  25648. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25649. this._setRayOnPointerInfo(pi);
  25650. this.onPointerObservable.notifyObservers(pi, type);
  25651. }
  25652. }
  25653. if (this.onPointerUp) {
  25654. this.onPointerUp(evt, pickResult, type);
  25655. }
  25656. return this;
  25657. };
  25658. /**
  25659. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25660. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25661. * @returns true if the pointer was captured
  25662. */
  25663. Scene.prototype.isPointerCaptured = function (pointerId) {
  25664. if (pointerId === void 0) { pointerId = 0; }
  25665. return this._pointerCaptures[pointerId];
  25666. };
  25667. /**
  25668. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25669. * @param attachUp defines if you want to attach events to pointerup
  25670. * @param attachDown defines if you want to attach events to pointerdown
  25671. * @param attachMove defines if you want to attach events to pointermove
  25672. */
  25673. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25674. var _this = this;
  25675. if (attachUp === void 0) { attachUp = true; }
  25676. if (attachDown === void 0) { attachDown = true; }
  25677. if (attachMove === void 0) { attachMove = true; }
  25678. this._initActionManager = function (act, clickInfo) {
  25679. if (!_this._meshPickProceed) {
  25680. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25681. _this._currentPickResult = pickResult;
  25682. if (pickResult) {
  25683. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25684. }
  25685. _this._meshPickProceed = true;
  25686. }
  25687. return act;
  25688. };
  25689. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25690. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25691. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25692. btn !== _this._previousButtonPressed) {
  25693. _this._doubleClickOccured = false;
  25694. clickInfo.singleClick = true;
  25695. clickInfo.ignore = false;
  25696. cb(clickInfo, _this._currentPickResult);
  25697. }
  25698. };
  25699. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25700. var clickInfo = new ClickInfo();
  25701. _this._currentPickResult = null;
  25702. var act = null;
  25703. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25704. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25705. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25706. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25707. act = _this._initActionManager(act, clickInfo);
  25708. if (act)
  25709. checkPicking = act.hasPickTriggers;
  25710. }
  25711. if (checkPicking) {
  25712. var btn = evt.button;
  25713. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25714. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25715. if (!clickInfo.hasSwiped) {
  25716. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25717. if (!checkSingleClickImmediately) {
  25718. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25719. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25720. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25721. act = _this._initActionManager(act, clickInfo);
  25722. if (act)
  25723. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25724. }
  25725. }
  25726. if (checkSingleClickImmediately) {
  25727. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25728. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25729. btn !== _this._previousButtonPressed) {
  25730. clickInfo.singleClick = true;
  25731. cb(clickInfo, _this._currentPickResult);
  25732. }
  25733. }
  25734. // at least one double click is required to be check and exclusive double click is enabled
  25735. else {
  25736. // wait that no double click has been raised during the double click delay
  25737. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25738. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25739. }
  25740. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25741. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25742. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25743. act = _this._initActionManager(act, clickInfo);
  25744. if (act)
  25745. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25746. }
  25747. if (checkDoubleClick) {
  25748. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25749. if (btn === _this._previousButtonPressed &&
  25750. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25751. !_this._doubleClickOccured) {
  25752. // pointer has not moved for 2 clicks, it's a double click
  25753. if (!clickInfo.hasSwiped &&
  25754. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25755. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25756. _this._previousStartingPointerTime = 0;
  25757. _this._doubleClickOccured = true;
  25758. clickInfo.doubleClick = true;
  25759. clickInfo.ignore = false;
  25760. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25761. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25762. }
  25763. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25764. cb(clickInfo, _this._currentPickResult);
  25765. }
  25766. // if the two successive clicks are too far, it's just two simple clicks
  25767. else {
  25768. _this._doubleClickOccured = false;
  25769. _this._previousStartingPointerTime = _this._startingPointerTime;
  25770. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25771. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25772. _this._previousButtonPressed = btn;
  25773. if (Scene.ExclusiveDoubleClickMode) {
  25774. if (_this._previousDelayedSimpleClickTimeout) {
  25775. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25776. }
  25777. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25778. cb(clickInfo, _this._previousPickResult);
  25779. }
  25780. else {
  25781. cb(clickInfo, _this._currentPickResult);
  25782. }
  25783. }
  25784. }
  25785. // just the first click of the double has been raised
  25786. else {
  25787. _this._doubleClickOccured = false;
  25788. _this._previousStartingPointerTime = _this._startingPointerTime;
  25789. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25790. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25791. _this._previousButtonPressed = btn;
  25792. }
  25793. }
  25794. }
  25795. }
  25796. clickInfo.ignore = true;
  25797. cb(clickInfo, _this._currentPickResult);
  25798. };
  25799. this._spritePredicate = function (sprite) {
  25800. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25801. };
  25802. this._onPointerMove = function (evt) {
  25803. _this._updatePointerPosition(evt);
  25804. // PreObservable support
  25805. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25806. return;
  25807. }
  25808. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25809. return;
  25810. }
  25811. if (!_this.pointerMovePredicate) {
  25812. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25813. }
  25814. // Meshes
  25815. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25816. _this._processPointerMove(pickResult, evt);
  25817. };
  25818. this._onPointerDown = function (evt) {
  25819. _this._totalPointersPressed++;
  25820. _this._pickedDownMesh = null;
  25821. _this._meshPickProceed = false;
  25822. _this._updatePointerPosition(evt);
  25823. if (_this.preventDefaultOnPointerDown && canvas) {
  25824. evt.preventDefault();
  25825. canvas.focus();
  25826. }
  25827. // PreObservable support
  25828. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25829. return;
  25830. }
  25831. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25832. return;
  25833. }
  25834. _this._pointerCaptures[evt.pointerId] = true;
  25835. _this._startingPointerPosition.x = _this._pointerX;
  25836. _this._startingPointerPosition.y = _this._pointerY;
  25837. _this._startingPointerTime = Date.now();
  25838. if (!_this.pointerDownPredicate) {
  25839. _this.pointerDownPredicate = function (mesh) {
  25840. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25841. };
  25842. }
  25843. // Meshes
  25844. _this._pickedDownMesh = null;
  25845. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25846. _this._processPointerDown(pickResult, evt);
  25847. // Sprites
  25848. _this._pickedDownSprite = null;
  25849. if (_this.spriteManagers.length > 0) {
  25850. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25851. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25852. if (pickResult.pickedSprite.actionManager) {
  25853. _this._pickedDownSprite = pickResult.pickedSprite;
  25854. switch (evt.button) {
  25855. case 0:
  25856. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25857. break;
  25858. case 1:
  25859. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25860. break;
  25861. case 2:
  25862. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25863. break;
  25864. }
  25865. if (pickResult.pickedSprite.actionManager) {
  25866. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25867. }
  25868. }
  25869. }
  25870. }
  25871. };
  25872. this._onPointerUp = function (evt) {
  25873. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25874. return; // So we need to test it the pointer down was pressed before.
  25875. }
  25876. _this._totalPointersPressed--;
  25877. _this._pickedUpMesh = null;
  25878. _this._meshPickProceed = false;
  25879. _this._updatePointerPosition(evt);
  25880. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25881. // PreObservable support
  25882. if (_this.onPrePointerObservable.hasObservers()) {
  25883. if (!clickInfo.ignore) {
  25884. if (!clickInfo.hasSwiped) {
  25885. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25886. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25887. return;
  25888. }
  25889. }
  25890. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25891. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25892. return;
  25893. }
  25894. }
  25895. }
  25896. }
  25897. else {
  25898. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25899. return;
  25900. }
  25901. }
  25902. }
  25903. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25904. return;
  25905. }
  25906. _this._pointerCaptures[evt.pointerId] = false;
  25907. if (!_this.pointerUpPredicate) {
  25908. _this.pointerUpPredicate = function (mesh) {
  25909. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25910. };
  25911. }
  25912. // Meshes
  25913. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25914. _this._initActionManager(null, clickInfo);
  25915. }
  25916. if (!pickResult) {
  25917. pickResult = _this._currentPickResult;
  25918. }
  25919. _this._processPointerUp(pickResult, evt, clickInfo);
  25920. // Sprites
  25921. if (!clickInfo.ignore) {
  25922. if (_this.spriteManagers.length > 0) {
  25923. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25924. if (spritePickResult) {
  25925. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25926. if (spritePickResult.pickedSprite.actionManager) {
  25927. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25928. if (spritePickResult.pickedSprite.actionManager) {
  25929. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25930. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25931. }
  25932. }
  25933. }
  25934. }
  25935. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25936. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25937. }
  25938. }
  25939. }
  25940. }
  25941. _this._previousPickResult = _this._currentPickResult;
  25942. });
  25943. };
  25944. this._onKeyDown = function (evt) {
  25945. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25946. if (_this.onPreKeyboardObservable.hasObservers()) {
  25947. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25948. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25949. if (pi.skipOnPointerObservable) {
  25950. return;
  25951. }
  25952. }
  25953. if (_this.onKeyboardObservable.hasObservers()) {
  25954. var pi = new BABYLON.KeyboardInfo(type, evt);
  25955. _this.onKeyboardObservable.notifyObservers(pi, type);
  25956. }
  25957. if (_this.actionManager) {
  25958. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25959. }
  25960. };
  25961. this._onKeyUp = function (evt) {
  25962. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25963. if (_this.onPreKeyboardObservable.hasObservers()) {
  25964. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25965. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25966. if (pi.skipOnPointerObservable) {
  25967. return;
  25968. }
  25969. }
  25970. if (_this.onKeyboardObservable.hasObservers()) {
  25971. var pi = new BABYLON.KeyboardInfo(type, evt);
  25972. _this.onKeyboardObservable.notifyObservers(pi, type);
  25973. }
  25974. if (_this.actionManager) {
  25975. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25976. }
  25977. };
  25978. var engine = this.getEngine();
  25979. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25980. if (!canvas) {
  25981. return;
  25982. }
  25983. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25984. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25985. });
  25986. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25987. if (!canvas) {
  25988. return;
  25989. }
  25990. canvas.removeEventListener("keydown", _this._onKeyDown);
  25991. canvas.removeEventListener("keyup", _this._onKeyUp);
  25992. });
  25993. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25994. var canvas = this._engine.getRenderingCanvas();
  25995. if (!canvas) {
  25996. return;
  25997. }
  25998. if (attachMove) {
  25999. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26000. // Wheel
  26001. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26002. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26003. }
  26004. if (attachDown) {
  26005. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26006. }
  26007. if (attachUp) {
  26008. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26009. }
  26010. canvas.tabIndex = 1;
  26011. };
  26012. /** Detaches all event handlers*/
  26013. Scene.prototype.detachControl = function () {
  26014. var engine = this.getEngine();
  26015. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26016. var canvas = engine.getRenderingCanvas();
  26017. if (!canvas) {
  26018. return;
  26019. }
  26020. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26021. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26022. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26023. if (this._onCanvasBlurObserver) {
  26024. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26025. }
  26026. if (this._onCanvasFocusObserver) {
  26027. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26028. }
  26029. // Wheel
  26030. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26031. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26032. // Keyboard
  26033. canvas.removeEventListener("keydown", this._onKeyDown);
  26034. canvas.removeEventListener("keyup", this._onKeyUp);
  26035. // Observables
  26036. this.onKeyboardObservable.clear();
  26037. this.onPreKeyboardObservable.clear();
  26038. this.onPointerObservable.clear();
  26039. this.onPrePointerObservable.clear();
  26040. };
  26041. /**
  26042. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26043. * Delay loaded resources are not taking in account
  26044. * @return true if all required resources are ready
  26045. */
  26046. Scene.prototype.isReady = function () {
  26047. if (this._isDisposed) {
  26048. return false;
  26049. }
  26050. if (this._pendingData.length > 0) {
  26051. return false;
  26052. }
  26053. var index;
  26054. var engine = this.getEngine();
  26055. // Geometries
  26056. for (index = 0; index < this.geometries.length; index++) {
  26057. var geometry = this.geometries[index];
  26058. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26059. return false;
  26060. }
  26061. }
  26062. // Meshes
  26063. for (index = 0; index < this.meshes.length; index++) {
  26064. var mesh = this.meshes[index];
  26065. if (!mesh.isEnabled()) {
  26066. continue;
  26067. }
  26068. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26069. continue;
  26070. }
  26071. if (!mesh.isReady(true)) {
  26072. return false;
  26073. }
  26074. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26075. // Is Ready For Mesh
  26076. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26077. var step = _a[_i];
  26078. if (!step.action(mesh, hardwareInstancedRendering)) {
  26079. return false;
  26080. }
  26081. }
  26082. }
  26083. // Post-processes
  26084. if (this.activeCameras && this.activeCameras.length > 0) {
  26085. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26086. var camera = _c[_b];
  26087. if (!camera.isReady(true)) {
  26088. return false;
  26089. }
  26090. }
  26091. }
  26092. else if (this.activeCamera) {
  26093. if (!this.activeCamera.isReady(true)) {
  26094. return false;
  26095. }
  26096. }
  26097. // Particles
  26098. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26099. var particleSystem = _e[_d];
  26100. if (!particleSystem.isReady()) {
  26101. return false;
  26102. }
  26103. }
  26104. return true;
  26105. };
  26106. /** Resets all cached information relative to material (including effect and visibility) */
  26107. Scene.prototype.resetCachedMaterial = function () {
  26108. this._cachedMaterial = null;
  26109. this._cachedEffect = null;
  26110. this._cachedVisibility = null;
  26111. };
  26112. /**
  26113. * Registers a function to be called before every frame render
  26114. * @param func defines the function to register
  26115. */
  26116. Scene.prototype.registerBeforeRender = function (func) {
  26117. this.onBeforeRenderObservable.add(func);
  26118. };
  26119. /**
  26120. * Unregisters a function called before every frame render
  26121. * @param func defines the function to unregister
  26122. */
  26123. Scene.prototype.unregisterBeforeRender = function (func) {
  26124. this.onBeforeRenderObservable.removeCallback(func);
  26125. };
  26126. /**
  26127. * Registers a function to be called after every frame render
  26128. * @param func defines the function to register
  26129. */
  26130. Scene.prototype.registerAfterRender = function (func) {
  26131. this.onAfterRenderObservable.add(func);
  26132. };
  26133. /**
  26134. * Unregisters a function called after every frame render
  26135. * @param func defines the function to unregister
  26136. */
  26137. Scene.prototype.unregisterAfterRender = function (func) {
  26138. this.onAfterRenderObservable.removeCallback(func);
  26139. };
  26140. Scene.prototype._executeOnceBeforeRender = function (func) {
  26141. var _this = this;
  26142. var execFunc = function () {
  26143. func();
  26144. setTimeout(function () {
  26145. _this.unregisterBeforeRender(execFunc);
  26146. });
  26147. };
  26148. this.registerBeforeRender(execFunc);
  26149. };
  26150. /**
  26151. * The provided function will run before render once and will be disposed afterwards.
  26152. * A timeout delay can be provided so that the function will be executed in N ms.
  26153. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26154. * @param func The function to be executed.
  26155. * @param timeout optional delay in ms
  26156. */
  26157. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26158. var _this = this;
  26159. if (timeout !== undefined) {
  26160. setTimeout(function () {
  26161. _this._executeOnceBeforeRender(func);
  26162. }, timeout);
  26163. }
  26164. else {
  26165. this._executeOnceBeforeRender(func);
  26166. }
  26167. };
  26168. /** @hidden */
  26169. Scene.prototype._addPendingData = function (data) {
  26170. this._pendingData.push(data);
  26171. };
  26172. /** @hidden */
  26173. Scene.prototype._removePendingData = function (data) {
  26174. var wasLoading = this.isLoading;
  26175. var index = this._pendingData.indexOf(data);
  26176. if (index !== -1) {
  26177. this._pendingData.splice(index, 1);
  26178. }
  26179. if (wasLoading && !this.isLoading) {
  26180. this.onDataLoadedObservable.notifyObservers(this);
  26181. }
  26182. };
  26183. /**
  26184. * Returns the number of items waiting to be loaded
  26185. * @returns the number of items waiting to be loaded
  26186. */
  26187. Scene.prototype.getWaitingItemsCount = function () {
  26188. return this._pendingData.length;
  26189. };
  26190. Object.defineProperty(Scene.prototype, "isLoading", {
  26191. /**
  26192. * Returns a boolean indicating if the scene is still loading data
  26193. */
  26194. get: function () {
  26195. return this._pendingData.length > 0;
  26196. },
  26197. enumerable: true,
  26198. configurable: true
  26199. });
  26200. /**
  26201. * Registers a function to be executed when the scene is ready
  26202. * @param {Function} func - the function to be executed
  26203. */
  26204. Scene.prototype.executeWhenReady = function (func) {
  26205. var _this = this;
  26206. this.onReadyObservable.add(func);
  26207. if (this._executeWhenReadyTimeoutId !== -1) {
  26208. return;
  26209. }
  26210. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26211. _this._checkIsReady();
  26212. }, 150);
  26213. };
  26214. /**
  26215. * Returns a promise that resolves when the scene is ready
  26216. * @returns A promise that resolves when the scene is ready
  26217. */
  26218. Scene.prototype.whenReadyAsync = function () {
  26219. var _this = this;
  26220. return new Promise(function (resolve) {
  26221. _this.executeWhenReady(function () {
  26222. resolve();
  26223. });
  26224. });
  26225. };
  26226. /** @hidden */
  26227. Scene.prototype._checkIsReady = function () {
  26228. var _this = this;
  26229. this._registerTransientComponents();
  26230. if (this.isReady()) {
  26231. this.onReadyObservable.notifyObservers(this);
  26232. this.onReadyObservable.clear();
  26233. this._executeWhenReadyTimeoutId = -1;
  26234. return;
  26235. }
  26236. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26237. _this._checkIsReady();
  26238. }, 150);
  26239. };
  26240. // Animations
  26241. /**
  26242. * Will start the animation sequence of a given target
  26243. * @param target defines the target
  26244. * @param from defines from which frame should animation start
  26245. * @param to defines until which frame should animation run.
  26246. * @param weight defines the weight to apply to the animation (1.0 by default)
  26247. * @param loop defines if the animation loops
  26248. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26249. * @param onAnimationEnd defines the function to be executed when the animation ends
  26250. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26251. * @returns the animatable object created for this animation
  26252. */
  26253. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26254. if (weight === void 0) { weight = 1.0; }
  26255. if (speedRatio === void 0) { speedRatio = 1.0; }
  26256. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26257. returnedAnimatable.weight = weight;
  26258. return returnedAnimatable;
  26259. };
  26260. /**
  26261. * Will start the animation sequence of a given target
  26262. * @param target defines the target
  26263. * @param from defines from which frame should animation start
  26264. * @param to defines until which frame should animation run.
  26265. * @param loop defines if the animation loops
  26266. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26267. * @param onAnimationEnd defines the function to be executed when the animation ends
  26268. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26269. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26270. * @returns the animatable object created for this animation
  26271. */
  26272. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26273. if (speedRatio === void 0) { speedRatio = 1.0; }
  26274. if (stopCurrent === void 0) { stopCurrent = true; }
  26275. if (from > to && speedRatio > 0) {
  26276. speedRatio *= -1;
  26277. }
  26278. if (stopCurrent) {
  26279. this.stopAnimation(target);
  26280. }
  26281. if (!animatable) {
  26282. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26283. }
  26284. // Local animations
  26285. if (target.animations) {
  26286. animatable.appendAnimations(target, target.animations);
  26287. }
  26288. // Children animations
  26289. if (target.getAnimatables) {
  26290. var animatables = target.getAnimatables();
  26291. for (var index = 0; index < animatables.length; index++) {
  26292. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26293. }
  26294. }
  26295. animatable.reset();
  26296. return animatable;
  26297. };
  26298. /**
  26299. * Begin a new animation on a given node
  26300. * @param target defines the target where the animation will take place
  26301. * @param animations defines the list of animations to start
  26302. * @param from defines the initial value
  26303. * @param to defines the final value
  26304. * @param loop defines if you want animation to loop (off by default)
  26305. * @param speedRatio defines the speed ratio to apply to all animations
  26306. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26307. * @returns the list of created animatables
  26308. */
  26309. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26310. if (speedRatio === undefined) {
  26311. speedRatio = 1.0;
  26312. }
  26313. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26314. return animatable;
  26315. };
  26316. /**
  26317. * Begin a new animation on a given node and its hierarchy
  26318. * @param target defines the root node where the animation will take place
  26319. * @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.
  26320. * @param animations defines the list of animations to start
  26321. * @param from defines the initial value
  26322. * @param to defines the final value
  26323. * @param loop defines if you want animation to loop (off by default)
  26324. * @param speedRatio defines the speed ratio to apply to all animations
  26325. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26326. * @returns the list of animatables created for all nodes
  26327. */
  26328. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26329. var children = target.getDescendants(directDescendantsOnly);
  26330. var result = [];
  26331. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26332. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26333. var child = children_1[_i];
  26334. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26335. }
  26336. return result;
  26337. };
  26338. /**
  26339. * Gets the animatable associated with a specific target
  26340. * @param target defines the target of the animatable
  26341. * @returns the required animatable if found
  26342. */
  26343. Scene.prototype.getAnimatableByTarget = function (target) {
  26344. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26345. if (this._activeAnimatables[index].target === target) {
  26346. return this._activeAnimatables[index];
  26347. }
  26348. }
  26349. return null;
  26350. };
  26351. /**
  26352. * Gets all animatables associated with a given target
  26353. * @param target defines the target to look animatables for
  26354. * @returns an array of Animatables
  26355. */
  26356. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26357. var result = [];
  26358. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26359. if (this._activeAnimatables[index].target === target) {
  26360. result.push(this._activeAnimatables[index]);
  26361. }
  26362. }
  26363. return result;
  26364. };
  26365. Object.defineProperty(Scene.prototype, "animatables", {
  26366. /**
  26367. * Gets all animatable attached to the scene
  26368. */
  26369. get: function () {
  26370. return this._activeAnimatables;
  26371. },
  26372. enumerable: true,
  26373. configurable: true
  26374. });
  26375. /**
  26376. * Will stop the animation of the given target
  26377. * @param target - the target
  26378. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26379. */
  26380. Scene.prototype.stopAnimation = function (target, animationName) {
  26381. var animatables = this.getAllAnimatablesByTarget(target);
  26382. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26383. var animatable = animatables_1[_i];
  26384. animatable.stop(animationName);
  26385. }
  26386. };
  26387. /**
  26388. * Stops and removes all animations that have been applied to the scene
  26389. */
  26390. Scene.prototype.stopAllAnimations = function () {
  26391. if (this._activeAnimatables) {
  26392. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26393. this._activeAnimatables[i].stop();
  26394. }
  26395. this._activeAnimatables = [];
  26396. }
  26397. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26398. var group = _a[_i];
  26399. group.stop();
  26400. }
  26401. };
  26402. Scene.prototype._animate = function () {
  26403. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26404. return;
  26405. }
  26406. // Getting time
  26407. var now = BABYLON.Tools.Now;
  26408. if (!this._animationTimeLast) {
  26409. if (this._pendingData.length > 0) {
  26410. return;
  26411. }
  26412. this._animationTimeLast = now;
  26413. }
  26414. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26415. this._animationTime += deltaTime;
  26416. this._animationTimeLast = now;
  26417. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26418. this._activeAnimatables[index]._animate(this._animationTime);
  26419. }
  26420. // Late animation bindings
  26421. this._processLateAnimationBindings();
  26422. };
  26423. /** @hidden */
  26424. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26425. var target = runtimeAnimation.target;
  26426. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26427. if (!target._lateAnimationHolders) {
  26428. target._lateAnimationHolders = {};
  26429. }
  26430. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26431. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26432. totalWeight: 0,
  26433. animations: [],
  26434. originalValue: originalValue
  26435. };
  26436. }
  26437. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26438. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26439. };
  26440. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26441. var normalizer = 1.0;
  26442. var finalPosition = BABYLON.Tmp.Vector3[0];
  26443. var finalScaling = BABYLON.Tmp.Vector3[1];
  26444. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26445. var startIndex = 0;
  26446. var originalAnimation = holder.animations[0];
  26447. var originalValue = holder.originalValue;
  26448. var scale = 1;
  26449. if (holder.totalWeight < 1.0) {
  26450. // We need to mix the original value in
  26451. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26452. scale = 1.0 - holder.totalWeight;
  26453. }
  26454. else {
  26455. startIndex = 1;
  26456. // We need to normalize the weights
  26457. normalizer = holder.totalWeight;
  26458. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26459. scale = originalAnimation.weight / normalizer;
  26460. if (scale == 1) {
  26461. return originalAnimation.currentValue;
  26462. }
  26463. }
  26464. finalScaling.scaleInPlace(scale);
  26465. finalPosition.scaleInPlace(scale);
  26466. finalQuaternion.scaleInPlace(scale);
  26467. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26468. var runtimeAnimation = holder.animations[animIndex];
  26469. var scale = runtimeAnimation.weight / normalizer;
  26470. var currentPosition = BABYLON.Tmp.Vector3[2];
  26471. var currentScaling = BABYLON.Tmp.Vector3[3];
  26472. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26473. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26474. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26475. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26476. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26477. }
  26478. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26479. return originalAnimation._workValue;
  26480. };
  26481. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26482. var originalAnimation = holder.animations[0];
  26483. var originalValue = holder.originalValue;
  26484. if (holder.animations.length === 1) {
  26485. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26486. }
  26487. var normalizer = 1.0;
  26488. var quaternions;
  26489. var weights;
  26490. if (holder.totalWeight < 1.0) {
  26491. var scale = 1.0 - holder.totalWeight;
  26492. quaternions = [];
  26493. weights = [];
  26494. quaternions.push(originalValue);
  26495. weights.push(scale);
  26496. }
  26497. else {
  26498. if (holder.animations.length === 2) { // Slerp as soon as we can
  26499. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26500. }
  26501. quaternions = [];
  26502. weights = [];
  26503. normalizer = holder.totalWeight;
  26504. }
  26505. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26506. var runtimeAnimation = holder.animations[animIndex];
  26507. quaternions.push(runtimeAnimation.currentValue);
  26508. weights.push(runtimeAnimation.weight / normalizer);
  26509. }
  26510. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26511. var cumulativeAmount = 0;
  26512. var cumulativeQuaternion = null;
  26513. for (var index = 0; index < quaternions.length;) {
  26514. if (!cumulativeQuaternion) {
  26515. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26516. cumulativeAmount = weights[index] + weights[index + 1];
  26517. index += 2;
  26518. continue;
  26519. }
  26520. cumulativeAmount += weights[index];
  26521. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26522. index++;
  26523. }
  26524. return cumulativeQuaternion;
  26525. };
  26526. Scene.prototype._processLateAnimationBindings = function () {
  26527. if (!this._registeredForLateAnimationBindings.length) {
  26528. return;
  26529. }
  26530. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26531. var target = this._registeredForLateAnimationBindings.data[index];
  26532. for (var path in target._lateAnimationHolders) {
  26533. var holder = target._lateAnimationHolders[path];
  26534. var originalAnimation = holder.animations[0];
  26535. var originalValue = holder.originalValue;
  26536. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26537. var finalValue = void 0;
  26538. if (matrixDecomposeMode) {
  26539. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26540. }
  26541. else {
  26542. var quaternionMode = originalValue.w !== undefined;
  26543. if (quaternionMode) {
  26544. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26545. }
  26546. else {
  26547. var startIndex = 0;
  26548. var normalizer = 1.0;
  26549. if (holder.totalWeight < 1.0) {
  26550. // We need to mix the original value in
  26551. if (originalValue.scale) {
  26552. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26553. }
  26554. else {
  26555. finalValue = originalValue * (1.0 - holder.totalWeight);
  26556. }
  26557. }
  26558. else {
  26559. // We need to normalize the weights
  26560. normalizer = holder.totalWeight;
  26561. var scale_1 = originalAnimation.weight / normalizer;
  26562. if (scale_1 !== 1) {
  26563. if (originalAnimation.currentValue.scale) {
  26564. finalValue = originalAnimation.currentValue.scale(scale_1);
  26565. }
  26566. else {
  26567. finalValue = originalAnimation.currentValue * scale_1;
  26568. }
  26569. }
  26570. else {
  26571. finalValue = originalAnimation.currentValue;
  26572. }
  26573. startIndex = 1;
  26574. }
  26575. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26576. var runtimeAnimation = holder.animations[animIndex];
  26577. var scale = runtimeAnimation.weight / normalizer;
  26578. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26579. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26580. }
  26581. else {
  26582. finalValue += runtimeAnimation.currentValue * scale;
  26583. }
  26584. }
  26585. }
  26586. }
  26587. target[path] = finalValue;
  26588. }
  26589. target._lateAnimationHolders = {};
  26590. }
  26591. this._registeredForLateAnimationBindings.reset();
  26592. };
  26593. // Matrix
  26594. /** @hidden */
  26595. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26596. this._useAlternateCameraConfiguration = active;
  26597. };
  26598. /**
  26599. * Gets the current view matrix
  26600. * @returns a Matrix
  26601. */
  26602. Scene.prototype.getViewMatrix = function () {
  26603. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26604. };
  26605. /**
  26606. * Gets the current projection matrix
  26607. * @returns a Matrix
  26608. */
  26609. Scene.prototype.getProjectionMatrix = function () {
  26610. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26611. };
  26612. /**
  26613. * Gets the current transform matrix
  26614. * @returns a Matrix made of View * Projection
  26615. */
  26616. Scene.prototype.getTransformMatrix = function () {
  26617. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26618. };
  26619. /**
  26620. * Sets the current transform matrix
  26621. * @param view defines the View matrix to use
  26622. * @param projection defines the Projection matrix to use
  26623. */
  26624. Scene.prototype.setTransformMatrix = function (view, projection) {
  26625. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26626. return;
  26627. }
  26628. this._viewUpdateFlag = view.updateFlag;
  26629. this._projectionUpdateFlag = projection.updateFlag;
  26630. this._viewMatrix = view;
  26631. this._projectionMatrix = projection;
  26632. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26633. // Update frustum
  26634. if (!this._frustumPlanes) {
  26635. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26636. }
  26637. else {
  26638. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26639. }
  26640. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26641. var otherCamera = this.activeCamera._alternateCamera;
  26642. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26643. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26644. }
  26645. if (this._sceneUbo.useUbo) {
  26646. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26647. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26648. this._sceneUbo.update();
  26649. }
  26650. };
  26651. /** @hidden */
  26652. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26653. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26654. return;
  26655. }
  26656. this._alternateViewUpdateFlag = view.updateFlag;
  26657. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26658. this._alternateViewMatrix = view;
  26659. this._alternateProjectionMatrix = projection;
  26660. if (!this._alternateTransformMatrix) {
  26661. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26662. }
  26663. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26664. if (!this._alternateSceneUbo) {
  26665. this._createAlternateUbo();
  26666. }
  26667. if (this._alternateSceneUbo.useUbo) {
  26668. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26669. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26670. this._alternateSceneUbo.update();
  26671. }
  26672. };
  26673. /**
  26674. * Gets the uniform buffer used to store scene data
  26675. * @returns a UniformBuffer
  26676. */
  26677. Scene.prototype.getSceneUniformBuffer = function () {
  26678. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26679. };
  26680. /**
  26681. * Gets an unique (relatively to the current scene) Id
  26682. * @returns an unique number for the scene
  26683. */
  26684. Scene.prototype.getUniqueId = function () {
  26685. var result = Scene._uniqueIdCounter;
  26686. Scene._uniqueIdCounter++;
  26687. return result;
  26688. };
  26689. /**
  26690. * Add a mesh to the list of scene's meshes
  26691. * @param newMesh defines the mesh to add
  26692. * @param recursive if all child meshes should also be added to the scene
  26693. */
  26694. Scene.prototype.addMesh = function (newMesh, recursive) {
  26695. var _this = this;
  26696. if (recursive === void 0) { recursive = false; }
  26697. this.meshes.push(newMesh);
  26698. //notify the collision coordinator
  26699. if (this.collisionCoordinator) {
  26700. this.collisionCoordinator.onMeshAdded(newMesh);
  26701. }
  26702. newMesh._resyncLightSources();
  26703. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26704. if (recursive) {
  26705. newMesh.getChildMeshes().forEach(function (m) {
  26706. _this.addMesh(m);
  26707. });
  26708. }
  26709. };
  26710. /**
  26711. * Remove a mesh for the list of scene's meshes
  26712. * @param toRemove defines the mesh to remove
  26713. * @param recursive if all child meshes should also be removed from the scene
  26714. * @returns the index where the mesh was in the mesh list
  26715. */
  26716. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26717. var _this = this;
  26718. if (recursive === void 0) { recursive = false; }
  26719. var index = this.meshes.indexOf(toRemove);
  26720. if (index !== -1) {
  26721. // Remove from the scene if mesh found
  26722. this.meshes.splice(index, 1);
  26723. }
  26724. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26725. if (recursive) {
  26726. toRemove.getChildMeshes().forEach(function (m) {
  26727. _this.removeMesh(m);
  26728. });
  26729. }
  26730. return index;
  26731. };
  26732. /**
  26733. * Add a transform node to the list of scene's transform nodes
  26734. * @param newTransformNode defines the transform node to add
  26735. */
  26736. Scene.prototype.addTransformNode = function (newTransformNode) {
  26737. this.transformNodes.push(newTransformNode);
  26738. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26739. };
  26740. /**
  26741. * Remove a transform node for the list of scene's transform nodes
  26742. * @param toRemove defines the transform node to remove
  26743. * @returns the index where the transform node was in the transform node list
  26744. */
  26745. Scene.prototype.removeTransformNode = function (toRemove) {
  26746. var index = this.transformNodes.indexOf(toRemove);
  26747. if (index !== -1) {
  26748. // Remove from the scene if found
  26749. this.transformNodes.splice(index, 1);
  26750. }
  26751. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26752. return index;
  26753. };
  26754. /**
  26755. * Remove a skeleton for the list of scene's skeletons
  26756. * @param toRemove defines the skeleton to remove
  26757. * @returns the index where the skeleton was in the skeleton list
  26758. */
  26759. Scene.prototype.removeSkeleton = function (toRemove) {
  26760. var index = this.skeletons.indexOf(toRemove);
  26761. if (index !== -1) {
  26762. // Remove from the scene if found
  26763. this.skeletons.splice(index, 1);
  26764. }
  26765. return index;
  26766. };
  26767. /**
  26768. * Remove a morph target for the list of scene's morph targets
  26769. * @param toRemove defines the morph target to remove
  26770. * @returns the index where the morph target was in the morph target list
  26771. */
  26772. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26773. var index = this.morphTargetManagers.indexOf(toRemove);
  26774. if (index !== -1) {
  26775. // Remove from the scene if found
  26776. this.morphTargetManagers.splice(index, 1);
  26777. }
  26778. return index;
  26779. };
  26780. /**
  26781. * Remove a light for the list of scene's lights
  26782. * @param toRemove defines the light to remove
  26783. * @returns the index where the light was in the light list
  26784. */
  26785. Scene.prototype.removeLight = function (toRemove) {
  26786. var index = this.lights.indexOf(toRemove);
  26787. if (index !== -1) {
  26788. // Remove from meshes
  26789. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26790. var mesh = _a[_i];
  26791. mesh._removeLightSource(toRemove);
  26792. }
  26793. // Remove from the scene if mesh found
  26794. this.lights.splice(index, 1);
  26795. this.sortLightsByPriority();
  26796. }
  26797. this.onLightRemovedObservable.notifyObservers(toRemove);
  26798. return index;
  26799. };
  26800. /**
  26801. * Remove a camera for the list of scene's cameras
  26802. * @param toRemove defines the camera to remove
  26803. * @returns the index where the camera was in the camera list
  26804. */
  26805. Scene.prototype.removeCamera = function (toRemove) {
  26806. var index = this.cameras.indexOf(toRemove);
  26807. if (index !== -1) {
  26808. // Remove from the scene if mesh found
  26809. this.cameras.splice(index, 1);
  26810. }
  26811. // Remove from activeCameras
  26812. var index2 = this.activeCameras.indexOf(toRemove);
  26813. if (index2 !== -1) {
  26814. // Remove from the scene if mesh found
  26815. this.activeCameras.splice(index2, 1);
  26816. }
  26817. // Reset the activeCamera
  26818. if (this.activeCamera === toRemove) {
  26819. if (this.cameras.length > 0) {
  26820. this.activeCamera = this.cameras[0];
  26821. }
  26822. else {
  26823. this.activeCamera = null;
  26824. }
  26825. }
  26826. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26827. return index;
  26828. };
  26829. /**
  26830. * Remove a particle system for the list of scene's particle systems
  26831. * @param toRemove defines the particle system to remove
  26832. * @returns the index where the particle system was in the particle system list
  26833. */
  26834. Scene.prototype.removeParticleSystem = function (toRemove) {
  26835. var index = this.particleSystems.indexOf(toRemove);
  26836. if (index !== -1) {
  26837. this.particleSystems.splice(index, 1);
  26838. }
  26839. return index;
  26840. };
  26841. /**
  26842. * Remove a animation for the list of scene's animations
  26843. * @param toRemove defines the animation to remove
  26844. * @returns the index where the animation was in the animation list
  26845. */
  26846. Scene.prototype.removeAnimation = function (toRemove) {
  26847. var index = this.animations.indexOf(toRemove);
  26848. if (index !== -1) {
  26849. this.animations.splice(index, 1);
  26850. }
  26851. return index;
  26852. };
  26853. /**
  26854. * Removes the given animation group from this scene.
  26855. * @param toRemove The animation group to remove
  26856. * @returns The index of the removed animation group
  26857. */
  26858. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26859. var index = this.animationGroups.indexOf(toRemove);
  26860. if (index !== -1) {
  26861. this.animationGroups.splice(index, 1);
  26862. }
  26863. return index;
  26864. };
  26865. /**
  26866. * Removes the given multi-material from this scene.
  26867. * @param toRemove The multi-material to remove
  26868. * @returns The index of the removed multi-material
  26869. */
  26870. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26871. var index = this.multiMaterials.indexOf(toRemove);
  26872. if (index !== -1) {
  26873. this.multiMaterials.splice(index, 1);
  26874. }
  26875. return index;
  26876. };
  26877. /**
  26878. * Removes the given material from this scene.
  26879. * @param toRemove The material to remove
  26880. * @returns The index of the removed material
  26881. */
  26882. Scene.prototype.removeMaterial = function (toRemove) {
  26883. var index = this.materials.indexOf(toRemove);
  26884. if (index !== -1) {
  26885. this.materials.splice(index, 1);
  26886. }
  26887. return index;
  26888. };
  26889. /**
  26890. * Removes the given action manager from this scene.
  26891. * @param toRemove The action manager to remove
  26892. * @returns The index of the removed action manager
  26893. */
  26894. Scene.prototype.removeActionManager = function (toRemove) {
  26895. var index = this.actionManagers.indexOf(toRemove);
  26896. if (index !== -1) {
  26897. this.actionManagers.splice(index, 1);
  26898. }
  26899. return index;
  26900. };
  26901. /**
  26902. * Removes the given texture from this scene.
  26903. * @param toRemove The texture to remove
  26904. * @returns The index of the removed texture
  26905. */
  26906. Scene.prototype.removeTexture = function (toRemove) {
  26907. var index = this.textures.indexOf(toRemove);
  26908. if (index !== -1) {
  26909. this.textures.splice(index, 1);
  26910. }
  26911. return index;
  26912. };
  26913. /**
  26914. * Adds the given light to this scene
  26915. * @param newLight The light to add
  26916. */
  26917. Scene.prototype.addLight = function (newLight) {
  26918. this.lights.push(newLight);
  26919. this.sortLightsByPriority();
  26920. // Add light to all meshes (To support if the light is removed and then readded)
  26921. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26922. var mesh = _a[_i];
  26923. if (mesh._lightSources.indexOf(newLight) === -1) {
  26924. mesh._lightSources.push(newLight);
  26925. mesh._resyncLightSources();
  26926. }
  26927. }
  26928. this.onNewLightAddedObservable.notifyObservers(newLight);
  26929. };
  26930. /**
  26931. * Sorts the list list based on light priorities
  26932. */
  26933. Scene.prototype.sortLightsByPriority = function () {
  26934. if (this.requireLightSorting) {
  26935. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26936. }
  26937. };
  26938. /**
  26939. * Adds the given camera to this scene
  26940. * @param newCamera The camera to add
  26941. */
  26942. Scene.prototype.addCamera = function (newCamera) {
  26943. this.cameras.push(newCamera);
  26944. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26945. };
  26946. /**
  26947. * Adds the given skeleton to this scene
  26948. * @param newSkeleton The skeleton to add
  26949. */
  26950. Scene.prototype.addSkeleton = function (newSkeleton) {
  26951. this.skeletons.push(newSkeleton);
  26952. };
  26953. /**
  26954. * Adds the given particle system to this scene
  26955. * @param newParticleSystem The particle system to add
  26956. */
  26957. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26958. this.particleSystems.push(newParticleSystem);
  26959. };
  26960. /**
  26961. * Adds the given animation to this scene
  26962. * @param newAnimation The animation to add
  26963. */
  26964. Scene.prototype.addAnimation = function (newAnimation) {
  26965. this.animations.push(newAnimation);
  26966. };
  26967. /**
  26968. * Adds the given animation group to this scene.
  26969. * @param newAnimationGroup The animation group to add
  26970. */
  26971. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26972. this.animationGroups.push(newAnimationGroup);
  26973. };
  26974. /**
  26975. * Adds the given multi-material to this scene
  26976. * @param newMultiMaterial The multi-material to add
  26977. */
  26978. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26979. this.multiMaterials.push(newMultiMaterial);
  26980. };
  26981. /**
  26982. * Adds the given material to this scene
  26983. * @param newMaterial The material to add
  26984. */
  26985. Scene.prototype.addMaterial = function (newMaterial) {
  26986. this.materials.push(newMaterial);
  26987. };
  26988. /**
  26989. * Adds the given morph target to this scene
  26990. * @param newMorphTargetManager The morph target to add
  26991. */
  26992. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26993. this.morphTargetManagers.push(newMorphTargetManager);
  26994. };
  26995. /**
  26996. * Adds the given geometry to this scene
  26997. * @param newGeometry The geometry to add
  26998. */
  26999. Scene.prototype.addGeometry = function (newGeometry) {
  27000. this.geometries.push(newGeometry);
  27001. };
  27002. /**
  27003. * Adds the given action manager to this scene
  27004. * @param newActionManager The action manager to add
  27005. */
  27006. Scene.prototype.addActionManager = function (newActionManager) {
  27007. this.actionManagers.push(newActionManager);
  27008. };
  27009. /**
  27010. * Adds the given texture to this scene.
  27011. * @param newTexture The texture to add
  27012. */
  27013. Scene.prototype.addTexture = function (newTexture) {
  27014. this.textures.push(newTexture);
  27015. };
  27016. /**
  27017. * Switch active camera
  27018. * @param newCamera defines the new active camera
  27019. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27020. */
  27021. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27022. if (attachControl === void 0) { attachControl = true; }
  27023. var canvas = this._engine.getRenderingCanvas();
  27024. if (!canvas) {
  27025. return;
  27026. }
  27027. if (this.activeCamera) {
  27028. this.activeCamera.detachControl(canvas);
  27029. }
  27030. this.activeCamera = newCamera;
  27031. if (attachControl) {
  27032. newCamera.attachControl(canvas);
  27033. }
  27034. };
  27035. /**
  27036. * sets the active camera of the scene using its ID
  27037. * @param id defines the camera's ID
  27038. * @return the new active camera or null if none found.
  27039. */
  27040. Scene.prototype.setActiveCameraByID = function (id) {
  27041. var camera = this.getCameraByID(id);
  27042. if (camera) {
  27043. this.activeCamera = camera;
  27044. return camera;
  27045. }
  27046. return null;
  27047. };
  27048. /**
  27049. * sets the active camera of the scene using its name
  27050. * @param name defines the camera's name
  27051. * @returns the new active camera or null if none found.
  27052. */
  27053. Scene.prototype.setActiveCameraByName = function (name) {
  27054. var camera = this.getCameraByName(name);
  27055. if (camera) {
  27056. this.activeCamera = camera;
  27057. return camera;
  27058. }
  27059. return null;
  27060. };
  27061. /**
  27062. * get an animation group using its name
  27063. * @param name defines the material's name
  27064. * @return the animation group or null if none found.
  27065. */
  27066. Scene.prototype.getAnimationGroupByName = function (name) {
  27067. for (var index = 0; index < this.animationGroups.length; index++) {
  27068. if (this.animationGroups[index].name === name) {
  27069. return this.animationGroups[index];
  27070. }
  27071. }
  27072. return null;
  27073. };
  27074. /**
  27075. * get a material using its id
  27076. * @param id defines the material's ID
  27077. * @return the material or null if none found.
  27078. */
  27079. Scene.prototype.getMaterialByID = function (id) {
  27080. for (var index = 0; index < this.materials.length; index++) {
  27081. if (this.materials[index].id === id) {
  27082. return this.materials[index];
  27083. }
  27084. }
  27085. return null;
  27086. };
  27087. /**
  27088. * Gets a material using its name
  27089. * @param name defines the material's name
  27090. * @return the material or null if none found.
  27091. */
  27092. Scene.prototype.getMaterialByName = function (name) {
  27093. for (var index = 0; index < this.materials.length; index++) {
  27094. if (this.materials[index].name === name) {
  27095. return this.materials[index];
  27096. }
  27097. }
  27098. return null;
  27099. };
  27100. /**
  27101. * Gets a camera using its id
  27102. * @param id defines the id to look for
  27103. * @returns the camera or null if not found
  27104. */
  27105. Scene.prototype.getCameraByID = function (id) {
  27106. for (var index = 0; index < this.cameras.length; index++) {
  27107. if (this.cameras[index].id === id) {
  27108. return this.cameras[index];
  27109. }
  27110. }
  27111. return null;
  27112. };
  27113. /**
  27114. * Gets a camera using its unique id
  27115. * @param uniqueId defines the unique id to look for
  27116. * @returns the camera or null if not found
  27117. */
  27118. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27119. for (var index = 0; index < this.cameras.length; index++) {
  27120. if (this.cameras[index].uniqueId === uniqueId) {
  27121. return this.cameras[index];
  27122. }
  27123. }
  27124. return null;
  27125. };
  27126. /**
  27127. * Gets a camera using its name
  27128. * @param name defines the camera's name
  27129. * @return the camera or null if none found.
  27130. */
  27131. Scene.prototype.getCameraByName = function (name) {
  27132. for (var index = 0; index < this.cameras.length; index++) {
  27133. if (this.cameras[index].name === name) {
  27134. return this.cameras[index];
  27135. }
  27136. }
  27137. return null;
  27138. };
  27139. /**
  27140. * Gets a bone using its id
  27141. * @param id defines the bone's id
  27142. * @return the bone or null if not found
  27143. */
  27144. Scene.prototype.getBoneByID = function (id) {
  27145. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27146. var skeleton = this.skeletons[skeletonIndex];
  27147. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27148. if (skeleton.bones[boneIndex].id === id) {
  27149. return skeleton.bones[boneIndex];
  27150. }
  27151. }
  27152. }
  27153. return null;
  27154. };
  27155. /**
  27156. * Gets a bone using its id
  27157. * @param name defines the bone's name
  27158. * @return the bone or null if not found
  27159. */
  27160. Scene.prototype.getBoneByName = function (name) {
  27161. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27162. var skeleton = this.skeletons[skeletonIndex];
  27163. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27164. if (skeleton.bones[boneIndex].name === name) {
  27165. return skeleton.bones[boneIndex];
  27166. }
  27167. }
  27168. }
  27169. return null;
  27170. };
  27171. /**
  27172. * Gets a light node using its name
  27173. * @param name defines the the light's name
  27174. * @return the light or null if none found.
  27175. */
  27176. Scene.prototype.getLightByName = function (name) {
  27177. for (var index = 0; index < this.lights.length; index++) {
  27178. if (this.lights[index].name === name) {
  27179. return this.lights[index];
  27180. }
  27181. }
  27182. return null;
  27183. };
  27184. /**
  27185. * Gets a light node using its id
  27186. * @param id defines the light's id
  27187. * @return the light or null if none found.
  27188. */
  27189. Scene.prototype.getLightByID = function (id) {
  27190. for (var index = 0; index < this.lights.length; index++) {
  27191. if (this.lights[index].id === id) {
  27192. return this.lights[index];
  27193. }
  27194. }
  27195. return null;
  27196. };
  27197. /**
  27198. * Gets a light node using its scene-generated unique ID
  27199. * @param uniqueId defines the light's unique id
  27200. * @return the light or null if none found.
  27201. */
  27202. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27203. for (var index = 0; index < this.lights.length; index++) {
  27204. if (this.lights[index].uniqueId === uniqueId) {
  27205. return this.lights[index];
  27206. }
  27207. }
  27208. return null;
  27209. };
  27210. /**
  27211. * Gets a particle system by id
  27212. * @param id defines the particle system id
  27213. * @return the corresponding system or null if none found
  27214. */
  27215. Scene.prototype.getParticleSystemByID = function (id) {
  27216. for (var index = 0; index < this.particleSystems.length; index++) {
  27217. if (this.particleSystems[index].id === id) {
  27218. return this.particleSystems[index];
  27219. }
  27220. }
  27221. return null;
  27222. };
  27223. /**
  27224. * Gets a geometry using its ID
  27225. * @param id defines the geometry's id
  27226. * @return the geometry or null if none found.
  27227. */
  27228. Scene.prototype.getGeometryByID = function (id) {
  27229. for (var index = 0; index < this.geometries.length; index++) {
  27230. if (this.geometries[index].id === id) {
  27231. return this.geometries[index];
  27232. }
  27233. }
  27234. return null;
  27235. };
  27236. /**
  27237. * Add a new geometry to this scene
  27238. * @param geometry defines the geometry to be added to the scene.
  27239. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27240. * @return a boolean defining if the geometry was added or not
  27241. */
  27242. Scene.prototype.pushGeometry = function (geometry, force) {
  27243. if (!force && this.getGeometryByID(geometry.id)) {
  27244. return false;
  27245. }
  27246. this.geometries.push(geometry);
  27247. //notify the collision coordinator
  27248. if (this.collisionCoordinator) {
  27249. this.collisionCoordinator.onGeometryAdded(geometry);
  27250. }
  27251. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27252. return true;
  27253. };
  27254. /**
  27255. * Removes an existing geometry
  27256. * @param geometry defines the geometry to be removed from the scene
  27257. * @return a boolean defining if the geometry was removed or not
  27258. */
  27259. Scene.prototype.removeGeometry = function (geometry) {
  27260. var index = this.geometries.indexOf(geometry);
  27261. if (index > -1) {
  27262. this.geometries.splice(index, 1);
  27263. //notify the collision coordinator
  27264. if (this.collisionCoordinator) {
  27265. this.collisionCoordinator.onGeometryDeleted(geometry);
  27266. }
  27267. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27268. return true;
  27269. }
  27270. return false;
  27271. };
  27272. /**
  27273. * Gets the list of geometries attached to the scene
  27274. * @returns an array of Geometry
  27275. */
  27276. Scene.prototype.getGeometries = function () {
  27277. return this.geometries;
  27278. };
  27279. /**
  27280. * Gets the first added mesh found of a given ID
  27281. * @param id defines the id to search for
  27282. * @return the mesh found or null if not found at all
  27283. */
  27284. Scene.prototype.getMeshByID = function (id) {
  27285. for (var index = 0; index < this.meshes.length; index++) {
  27286. if (this.meshes[index].id === id) {
  27287. return this.meshes[index];
  27288. }
  27289. }
  27290. return null;
  27291. };
  27292. /**
  27293. * Gets a list of meshes using their id
  27294. * @param id defines the id to search for
  27295. * @returns a list of meshes
  27296. */
  27297. Scene.prototype.getMeshesByID = function (id) {
  27298. return this.meshes.filter(function (m) {
  27299. return m.id === id;
  27300. });
  27301. };
  27302. /**
  27303. * Gets the first added transform node found of a given ID
  27304. * @param id defines the id to search for
  27305. * @return the found transform node or null if not found at all.
  27306. */
  27307. Scene.prototype.getTransformNodeByID = function (id) {
  27308. for (var index = 0; index < this.transformNodes.length; index++) {
  27309. if (this.transformNodes[index].id === id) {
  27310. return this.transformNodes[index];
  27311. }
  27312. }
  27313. return null;
  27314. };
  27315. /**
  27316. * Gets a list of transform nodes using their id
  27317. * @param id defines the id to search for
  27318. * @returns a list of transform nodes
  27319. */
  27320. Scene.prototype.getTransformNodesByID = function (id) {
  27321. return this.transformNodes.filter(function (m) {
  27322. return m.id === id;
  27323. });
  27324. };
  27325. /**
  27326. * Gets a mesh with its auto-generated unique id
  27327. * @param uniqueId defines the unique id to search for
  27328. * @return the found mesh or null if not found at all.
  27329. */
  27330. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27331. for (var index = 0; index < this.meshes.length; index++) {
  27332. if (this.meshes[index].uniqueId === uniqueId) {
  27333. return this.meshes[index];
  27334. }
  27335. }
  27336. return null;
  27337. };
  27338. /**
  27339. * Gets a the last added mesh using a given id
  27340. * @param id defines the id to search for
  27341. * @return the found mesh or null if not found at all.
  27342. */
  27343. Scene.prototype.getLastMeshByID = function (id) {
  27344. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27345. if (this.meshes[index].id === id) {
  27346. return this.meshes[index];
  27347. }
  27348. }
  27349. return null;
  27350. };
  27351. /**
  27352. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27353. * @param id defines the id to search for
  27354. * @return the found node or null if not found at all
  27355. */
  27356. Scene.prototype.getLastEntryByID = function (id) {
  27357. var index;
  27358. for (index = this.meshes.length - 1; index >= 0; index--) {
  27359. if (this.meshes[index].id === id) {
  27360. return this.meshes[index];
  27361. }
  27362. }
  27363. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27364. if (this.transformNodes[index].id === id) {
  27365. return this.transformNodes[index];
  27366. }
  27367. }
  27368. for (index = this.cameras.length - 1; index >= 0; index--) {
  27369. if (this.cameras[index].id === id) {
  27370. return this.cameras[index];
  27371. }
  27372. }
  27373. for (index = this.lights.length - 1; index >= 0; index--) {
  27374. if (this.lights[index].id === id) {
  27375. return this.lights[index];
  27376. }
  27377. }
  27378. return null;
  27379. };
  27380. /**
  27381. * Gets a node (Mesh, Camera, Light) using a given id
  27382. * @param id defines the id to search for
  27383. * @return the found node or null if not found at all
  27384. */
  27385. Scene.prototype.getNodeByID = function (id) {
  27386. var mesh = this.getMeshByID(id);
  27387. if (mesh) {
  27388. return mesh;
  27389. }
  27390. var light = this.getLightByID(id);
  27391. if (light) {
  27392. return light;
  27393. }
  27394. var camera = this.getCameraByID(id);
  27395. if (camera) {
  27396. return camera;
  27397. }
  27398. var bone = this.getBoneByID(id);
  27399. return bone;
  27400. };
  27401. /**
  27402. * Gets a node (Mesh, Camera, Light) using a given name
  27403. * @param name defines the name to search for
  27404. * @return the found node or null if not found at all.
  27405. */
  27406. Scene.prototype.getNodeByName = function (name) {
  27407. var mesh = this.getMeshByName(name);
  27408. if (mesh) {
  27409. return mesh;
  27410. }
  27411. var light = this.getLightByName(name);
  27412. if (light) {
  27413. return light;
  27414. }
  27415. var camera = this.getCameraByName(name);
  27416. if (camera) {
  27417. return camera;
  27418. }
  27419. var bone = this.getBoneByName(name);
  27420. return bone;
  27421. };
  27422. /**
  27423. * Gets a mesh using a given name
  27424. * @param name defines the name to search for
  27425. * @return the found mesh or null if not found at all.
  27426. */
  27427. Scene.prototype.getMeshByName = function (name) {
  27428. for (var index = 0; index < this.meshes.length; index++) {
  27429. if (this.meshes[index].name === name) {
  27430. return this.meshes[index];
  27431. }
  27432. }
  27433. return null;
  27434. };
  27435. /**
  27436. * Gets a transform node using a given name
  27437. * @param name defines the name to search for
  27438. * @return the found transform node or null if not found at all.
  27439. */
  27440. Scene.prototype.getTransformNodeByName = function (name) {
  27441. for (var index = 0; index < this.transformNodes.length; index++) {
  27442. if (this.transformNodes[index].name === name) {
  27443. return this.transformNodes[index];
  27444. }
  27445. }
  27446. return null;
  27447. };
  27448. /**
  27449. * Gets a sound using a given name
  27450. * @param name defines the name to search for
  27451. * @return the found sound or null if not found at all.
  27452. */
  27453. Scene.prototype.getSoundByName = function (name) {
  27454. var index;
  27455. if (BABYLON.AudioEngine) {
  27456. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27457. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27458. return this.mainSoundTrack.soundCollection[index];
  27459. }
  27460. }
  27461. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27462. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27463. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27464. return this.soundTracks[sdIndex].soundCollection[index];
  27465. }
  27466. }
  27467. }
  27468. }
  27469. return null;
  27470. };
  27471. /**
  27472. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27473. * @param id defines the id to search for
  27474. * @return the found skeleton or null if not found at all.
  27475. */
  27476. Scene.prototype.getLastSkeletonByID = function (id) {
  27477. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27478. if (this.skeletons[index].id === id) {
  27479. return this.skeletons[index];
  27480. }
  27481. }
  27482. return null;
  27483. };
  27484. /**
  27485. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27486. * @param id defines the id to search for
  27487. * @return the found skeleton or null if not found at all.
  27488. */
  27489. Scene.prototype.getSkeletonById = function (id) {
  27490. for (var index = 0; index < this.skeletons.length; index++) {
  27491. if (this.skeletons[index].id === id) {
  27492. return this.skeletons[index];
  27493. }
  27494. }
  27495. return null;
  27496. };
  27497. /**
  27498. * Gets a skeleton using a given name
  27499. * @param name defines the name to search for
  27500. * @return the found skeleton or null if not found at all.
  27501. */
  27502. Scene.prototype.getSkeletonByName = function (name) {
  27503. for (var index = 0; index < this.skeletons.length; index++) {
  27504. if (this.skeletons[index].name === name) {
  27505. return this.skeletons[index];
  27506. }
  27507. }
  27508. return null;
  27509. };
  27510. /**
  27511. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27512. * @param id defines the id to search for
  27513. * @return the found morph target manager or null if not found at all.
  27514. */
  27515. Scene.prototype.getMorphTargetManagerById = function (id) {
  27516. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27517. if (this.morphTargetManagers[index].uniqueId === id) {
  27518. return this.morphTargetManagers[index];
  27519. }
  27520. }
  27521. return null;
  27522. };
  27523. /**
  27524. * Gets a boolean indicating if the given mesh is active
  27525. * @param mesh defines the mesh to look for
  27526. * @returns true if the mesh is in the active list
  27527. */
  27528. Scene.prototype.isActiveMesh = function (mesh) {
  27529. return (this._activeMeshes.indexOf(mesh) !== -1);
  27530. };
  27531. Object.defineProperty(Scene.prototype, "uid", {
  27532. /**
  27533. * Return a unique id as a string which can serve as an identifier for the scene
  27534. */
  27535. get: function () {
  27536. if (!this._uid) {
  27537. this._uid = BABYLON.Tools.RandomId();
  27538. }
  27539. return this._uid;
  27540. },
  27541. enumerable: true,
  27542. configurable: true
  27543. });
  27544. /**
  27545. * Add an externaly attached data from its key.
  27546. * This method call will fail and return false, if such key already exists.
  27547. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27548. * @param key the unique key that identifies the data
  27549. * @param data the data object to associate to the key for this Engine instance
  27550. * @return true if no such key were already present and the data was added successfully, false otherwise
  27551. */
  27552. Scene.prototype.addExternalData = function (key, data) {
  27553. if (!this._externalData) {
  27554. this._externalData = new BABYLON.StringDictionary();
  27555. }
  27556. return this._externalData.add(key, data);
  27557. };
  27558. /**
  27559. * Get an externaly attached data from its key
  27560. * @param key the unique key that identifies the data
  27561. * @return the associated data, if present (can be null), or undefined if not present
  27562. */
  27563. Scene.prototype.getExternalData = function (key) {
  27564. if (!this._externalData) {
  27565. return null;
  27566. }
  27567. return this._externalData.get(key);
  27568. };
  27569. /**
  27570. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27571. * @param key the unique key that identifies the data
  27572. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27573. * @return the associated data, can be null if the factory returned null.
  27574. */
  27575. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27576. if (!this._externalData) {
  27577. this._externalData = new BABYLON.StringDictionary();
  27578. }
  27579. return this._externalData.getOrAddWithFactory(key, factory);
  27580. };
  27581. /**
  27582. * Remove an externaly attached data from the Engine instance
  27583. * @param key the unique key that identifies the data
  27584. * @return true if the data was successfully removed, false if it doesn't exist
  27585. */
  27586. Scene.prototype.removeExternalData = function (key) {
  27587. return this._externalData.remove(key);
  27588. };
  27589. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27590. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27591. if (mesh.showSubMeshesBoundingBox) {
  27592. var boundingInfo = subMesh.getBoundingInfo();
  27593. if (boundingInfo !== null && boundingInfo !== undefined) {
  27594. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27595. }
  27596. }
  27597. var material = subMesh.getMaterial();
  27598. if (material !== null && material !== undefined) {
  27599. // Render targets
  27600. if (material.getRenderTargetTextures !== undefined) {
  27601. if (this._processedMaterials.indexOf(material) === -1) {
  27602. this._processedMaterials.push(material);
  27603. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27604. }
  27605. }
  27606. // Dispatch
  27607. this._activeIndices.addCount(subMesh.indexCount, false);
  27608. this._renderingManager.dispatch(subMesh, mesh, material);
  27609. }
  27610. }
  27611. };
  27612. /**
  27613. * Clear the processed materials smart array preventing retention point in material dispose.
  27614. */
  27615. Scene.prototype.freeProcessedMaterials = function () {
  27616. this._processedMaterials.dispose();
  27617. };
  27618. /**
  27619. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27620. */
  27621. Scene.prototype.freeActiveMeshes = function () {
  27622. this._activeMeshes.dispose();
  27623. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27624. this.activeCamera._activeMeshes.dispose();
  27625. }
  27626. if (this.activeCameras) {
  27627. for (var i = 0; i < this.activeCameras.length; i++) {
  27628. var activeCamera = this.activeCameras[i];
  27629. if (activeCamera && activeCamera._activeMeshes) {
  27630. activeCamera._activeMeshes.dispose();
  27631. }
  27632. }
  27633. }
  27634. };
  27635. /**
  27636. * Clear the info related to rendering groups preventing retention points during dispose.
  27637. */
  27638. Scene.prototype.freeRenderingGroups = function () {
  27639. if (this._renderingManager) {
  27640. this._renderingManager.freeRenderingGroups();
  27641. }
  27642. if (this.textures) {
  27643. for (var i = 0; i < this.textures.length; i++) {
  27644. var texture = this.textures[i];
  27645. if (texture && texture.renderList) {
  27646. texture.freeRenderingGroups();
  27647. }
  27648. }
  27649. }
  27650. };
  27651. /** @hidden */
  27652. Scene.prototype._isInIntermediateRendering = function () {
  27653. return this._intermediateRendering;
  27654. };
  27655. /**
  27656. * Defines the current active mesh candidate provider
  27657. * @param provider defines the provider to use
  27658. */
  27659. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27660. this._activeMeshCandidateProvider = provider;
  27661. };
  27662. /**
  27663. * Gets the current active mesh candidate provider
  27664. * @returns the current active mesh candidate provider
  27665. */
  27666. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27667. return this._activeMeshCandidateProvider;
  27668. };
  27669. /**
  27670. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27671. * @returns the current scene
  27672. */
  27673. Scene.prototype.freezeActiveMeshes = function () {
  27674. if (!this.activeCamera) {
  27675. return this;
  27676. }
  27677. if (!this._frustumPlanes) {
  27678. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27679. }
  27680. this._evaluateActiveMeshes();
  27681. this._activeMeshesFrozen = true;
  27682. return this;
  27683. };
  27684. /**
  27685. * Use this function to restart evaluating active meshes on every frame
  27686. * @returns the current scene
  27687. */
  27688. Scene.prototype.unfreezeActiveMeshes = function () {
  27689. this._activeMeshesFrozen = false;
  27690. return this;
  27691. };
  27692. Scene.prototype._evaluateActiveMeshes = function () {
  27693. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27694. return;
  27695. }
  27696. if (!this.activeCamera) {
  27697. return;
  27698. }
  27699. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27700. this.activeCamera._activeMeshes.reset();
  27701. this._activeMeshes.reset();
  27702. this._renderingManager.reset();
  27703. this._processedMaterials.reset();
  27704. this._activeParticleSystems.reset();
  27705. this._activeSkeletons.reset();
  27706. this._softwareSkinnedMeshes.reset();
  27707. if (this._boundingBoxRenderer) {
  27708. this._boundingBoxRenderer.reset();
  27709. }
  27710. // Meshes
  27711. var meshes;
  27712. var len;
  27713. var checkIsEnabled = true;
  27714. // Determine mesh candidates
  27715. if (this._activeMeshCandidateProvider !== undefined) {
  27716. // Use _activeMeshCandidateProvider
  27717. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27718. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27719. if (meshes !== undefined) {
  27720. len = meshes.length;
  27721. }
  27722. else {
  27723. len = 0;
  27724. }
  27725. }
  27726. else if (this._selectionOctree !== undefined) {
  27727. // Octree
  27728. var selection = this._selectionOctree.select(this._frustumPlanes);
  27729. meshes = selection.data;
  27730. len = selection.length;
  27731. }
  27732. else {
  27733. // Full scene traversal
  27734. len = this.meshes.length;
  27735. meshes = this.meshes;
  27736. }
  27737. // Check each mesh
  27738. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27739. mesh = meshes[meshIndex];
  27740. if (mesh.isBlocked) {
  27741. continue;
  27742. }
  27743. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27744. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27745. continue;
  27746. }
  27747. mesh.computeWorldMatrix();
  27748. // Intersections
  27749. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27750. this._meshesForIntersections.pushNoDuplicate(mesh);
  27751. }
  27752. // Switch to current LOD
  27753. meshLOD = mesh.getLOD(this.activeCamera);
  27754. if (meshLOD === undefined || meshLOD === null) {
  27755. continue;
  27756. }
  27757. mesh._preActivate();
  27758. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27759. this._activeMeshes.push(mesh);
  27760. this.activeCamera._activeMeshes.push(mesh);
  27761. mesh._activate(this._renderId);
  27762. if (meshLOD !== mesh) {
  27763. meshLOD._activate(this._renderId);
  27764. }
  27765. this._activeMesh(mesh, meshLOD);
  27766. }
  27767. }
  27768. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27769. // Particle systems
  27770. if (this.particlesEnabled) {
  27771. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27772. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27773. var particleSystem = this.particleSystems[particleIndex];
  27774. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27775. continue;
  27776. }
  27777. var emitter = particleSystem.emitter;
  27778. if (!emitter.position || emitter.isEnabled()) {
  27779. this._activeParticleSystems.push(particleSystem);
  27780. particleSystem.animate();
  27781. this._renderingManager.dispatchParticles(particleSystem);
  27782. }
  27783. }
  27784. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27785. }
  27786. };
  27787. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27788. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27789. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27790. mesh.skeleton.prepare();
  27791. }
  27792. if (!mesh.computeBonesUsingShaders) {
  27793. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27794. }
  27795. }
  27796. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27797. var boundingInfo = sourceMesh.getBoundingInfo();
  27798. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27799. }
  27800. if (mesh !== undefined && mesh !== null
  27801. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27802. // Submeshes Octrees
  27803. var len;
  27804. var subMeshes;
  27805. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27806. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27807. len = intersections.length;
  27808. subMeshes = intersections.data;
  27809. }
  27810. else {
  27811. subMeshes = mesh.subMeshes;
  27812. len = subMeshes.length;
  27813. }
  27814. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27815. subMesh = subMeshes[subIndex];
  27816. this._evaluateSubMesh(subMesh, mesh);
  27817. }
  27818. }
  27819. };
  27820. /**
  27821. * Update the transform matrix to update from the current active camera
  27822. * @param force defines a boolean used to force the update even if cache is up to date
  27823. */
  27824. Scene.prototype.updateTransformMatrix = function (force) {
  27825. if (!this.activeCamera) {
  27826. return;
  27827. }
  27828. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27829. };
  27830. /**
  27831. * 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)
  27832. * @param alternateCamera defines the camera to use
  27833. */
  27834. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27835. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27836. };
  27837. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27838. if (camera && camera._skipRendering) {
  27839. return;
  27840. }
  27841. var engine = this._engine;
  27842. this.activeCamera = camera;
  27843. if (!this.activeCamera)
  27844. throw new Error("Active camera not set");
  27845. // Viewport
  27846. engine.setViewport(this.activeCamera.viewport);
  27847. // Camera
  27848. this.resetCachedMaterial();
  27849. this._renderId++;
  27850. this.updateTransformMatrix();
  27851. if (camera._alternateCamera) {
  27852. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27853. this._alternateRendering = true;
  27854. }
  27855. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27856. // Meshes
  27857. this._evaluateActiveMeshes();
  27858. // Software skinning
  27859. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27860. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27861. mesh.applySkeleton(mesh.skeleton);
  27862. }
  27863. // Render targets
  27864. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27865. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27866. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27867. }
  27868. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27869. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27870. }
  27871. if (this.renderTargetsEnabled) {
  27872. this._intermediateRendering = true;
  27873. if (this._renderTargets.length > 0) {
  27874. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27875. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27876. var renderTarget = this._renderTargets.data[renderIndex];
  27877. if (renderTarget._shouldRender()) {
  27878. this._renderId++;
  27879. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27880. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27881. }
  27882. }
  27883. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27884. this._renderId++;
  27885. }
  27886. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27887. var step = _a[_i];
  27888. step.action(this.activeCamera);
  27889. }
  27890. this._intermediateRendering = false;
  27891. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27892. }
  27893. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27894. // Prepare Frame
  27895. if (this.postProcessManager) {
  27896. this.postProcessManager._prepareFrame();
  27897. }
  27898. // Before Camera Draw
  27899. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27900. var step = _c[_b];
  27901. step.action(this.activeCamera);
  27902. }
  27903. // Render
  27904. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27905. this._renderingManager.render(null, null, true, true);
  27906. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27907. // After Camera Draw
  27908. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27909. var step = _e[_d];
  27910. step.action(this.activeCamera);
  27911. }
  27912. // Bounding boxes
  27913. if (this._boundingBoxRenderer) {
  27914. this._boundingBoxRenderer.render();
  27915. }
  27916. // Finalize frame
  27917. if (this.postProcessManager) {
  27918. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27919. }
  27920. // Reset some special arrays
  27921. this._renderTargets.reset();
  27922. this._alternateRendering = false;
  27923. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27924. };
  27925. Scene.prototype._processSubCameras = function (camera) {
  27926. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27927. this._renderForCamera(camera);
  27928. return;
  27929. }
  27930. // rig cameras
  27931. for (var index = 0; index < camera._rigCameras.length; index++) {
  27932. this._renderForCamera(camera._rigCameras[index], camera);
  27933. }
  27934. this.activeCamera = camera;
  27935. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27936. };
  27937. Scene.prototype._checkIntersections = function () {
  27938. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27939. var sourceMesh = this._meshesForIntersections.data[index];
  27940. if (!sourceMesh.actionManager) {
  27941. continue;
  27942. }
  27943. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27944. var action = sourceMesh.actionManager.actions[actionIndex];
  27945. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27946. var parameters = action.getTriggerParameter();
  27947. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27948. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27949. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27950. if (areIntersecting && currentIntersectionInProgress === -1) {
  27951. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27952. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27953. sourceMesh._intersectionsInProgress.push(otherMesh);
  27954. }
  27955. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27956. sourceMesh._intersectionsInProgress.push(otherMesh);
  27957. }
  27958. }
  27959. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27960. //They intersected, and now they don't.
  27961. //is this trigger an exit trigger? execute an event.
  27962. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27963. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27964. }
  27965. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27966. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27967. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27968. return otherMesh === parameterMesh;
  27969. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27970. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27971. }
  27972. }
  27973. }
  27974. }
  27975. }
  27976. };
  27977. /**
  27978. * Render the scene
  27979. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27980. */
  27981. Scene.prototype.render = function (updateCameras) {
  27982. if (updateCameras === void 0) { updateCameras = true; }
  27983. if (this.isDisposed) {
  27984. return;
  27985. }
  27986. // Register components that have been associated lately to the scene.
  27987. this._registerTransientComponents();
  27988. this._activeParticles.fetchNewFrame();
  27989. this._totalVertices.fetchNewFrame();
  27990. this._activeIndices.fetchNewFrame();
  27991. this._activeBones.fetchNewFrame();
  27992. this._meshesForIntersections.reset();
  27993. this.resetCachedMaterial();
  27994. this.onBeforeAnimationsObservable.notifyObservers(this);
  27995. // Actions
  27996. if (this.actionManager) {
  27997. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27998. }
  27999. //Simplification Queue
  28000. if (this.simplificationQueue && !this.simplificationQueue.running) {
  28001. this.simplificationQueue.executeNext();
  28002. }
  28003. if (this._engine.isDeterministicLockStep()) {
  28004. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28005. var defaultFPS = (60.0 / 1000.0);
  28006. var defaultFrameTime = 1000 / 60; // frame time in MS
  28007. if (this._physicsEngine) {
  28008. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  28009. }
  28010. var stepsTaken = 0;
  28011. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28012. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28013. internalSteps = Math.min(internalSteps, maxSubSteps);
  28014. do {
  28015. this.onBeforeStepObservable.notifyObservers(this);
  28016. // Animations
  28017. this._animationRatio = defaultFrameTime * defaultFPS;
  28018. this._animate();
  28019. this.onAfterAnimationsObservable.notifyObservers(this);
  28020. // Physics
  28021. if (this._physicsEngine) {
  28022. this.onBeforePhysicsObservable.notifyObservers(this);
  28023. this._physicsEngine._step(defaultFrameTime / 1000);
  28024. this.onAfterPhysicsObservable.notifyObservers(this);
  28025. }
  28026. this.onAfterStepObservable.notifyObservers(this);
  28027. this._currentStepId++;
  28028. stepsTaken++;
  28029. deltaTime -= defaultFrameTime;
  28030. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28031. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28032. }
  28033. else {
  28034. // Animations
  28035. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28036. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28037. this._animate();
  28038. this.onAfterAnimationsObservable.notifyObservers(this);
  28039. // Physics
  28040. if (this._physicsEngine) {
  28041. this.onBeforePhysicsObservable.notifyObservers(this);
  28042. this._physicsEngine._step(deltaTime / 1000.0);
  28043. this.onAfterPhysicsObservable.notifyObservers(this);
  28044. }
  28045. }
  28046. // update gamepad manager
  28047. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28048. this._gamepadManager._checkGamepadsStatus();
  28049. }
  28050. // Update Cameras
  28051. if (updateCameras) {
  28052. if (this.activeCameras.length > 0) {
  28053. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28054. var camera = this.activeCameras[cameraIndex];
  28055. camera.update();
  28056. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28057. // rig cameras
  28058. for (var index = 0; index < camera._rigCameras.length; index++) {
  28059. camera._rigCameras[index].update();
  28060. }
  28061. }
  28062. }
  28063. }
  28064. else if (this.activeCamera) {
  28065. this.activeCamera.update();
  28066. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28067. // rig cameras
  28068. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28069. this.activeCamera._rigCameras[index].update();
  28070. }
  28071. }
  28072. }
  28073. }
  28074. // Before render
  28075. this.onBeforeRenderObservable.notifyObservers(this);
  28076. // Customs render targets
  28077. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28078. var engine = this.getEngine();
  28079. var currentActiveCamera = this.activeCamera;
  28080. if (this.renderTargetsEnabled) {
  28081. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28082. this._intermediateRendering = true;
  28083. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28084. var renderTarget = this.customRenderTargets[customIndex];
  28085. if (renderTarget._shouldRender()) {
  28086. this._renderId++;
  28087. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28088. if (!this.activeCamera)
  28089. throw new Error("Active camera not set");
  28090. // Viewport
  28091. engine.setViewport(this.activeCamera.viewport);
  28092. // Camera
  28093. this.updateTransformMatrix();
  28094. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28095. }
  28096. }
  28097. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28098. this._intermediateRendering = false;
  28099. this._renderId++;
  28100. }
  28101. // Restore back buffer
  28102. if (this.customRenderTargets.length > 0) {
  28103. engine.restoreDefaultFramebuffer();
  28104. }
  28105. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28106. this.activeCamera = currentActiveCamera;
  28107. // Procedural textures
  28108. if (this.proceduralTexturesEnabled) {
  28109. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28110. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28111. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28112. if (proceduralTexture._shouldRender()) {
  28113. proceduralTexture.render();
  28114. }
  28115. }
  28116. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28117. }
  28118. // Clear
  28119. if (this.autoClearDepthAndStencil || this.autoClear) {
  28120. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28121. }
  28122. // Shadows
  28123. if (this.shadowsEnabled) {
  28124. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28125. var light = this.lights[lightIndex];
  28126. var shadowGenerator = light.getShadowGenerator();
  28127. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28128. var shadowMap = (shadowGenerator.getShadowMap());
  28129. if (this.textures.indexOf(shadowMap) !== -1) {
  28130. this._renderTargets.push(shadowMap);
  28131. }
  28132. }
  28133. }
  28134. }
  28135. // Depth renderer
  28136. for (var key in this._depthRenderer) {
  28137. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28138. }
  28139. // Geometry renderer
  28140. if (this._geometryBufferRenderer) {
  28141. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28142. }
  28143. // RenderPipeline
  28144. if (this._postProcessRenderPipelineManager) {
  28145. this._postProcessRenderPipelineManager.update();
  28146. }
  28147. // Multi-cameras?
  28148. if (this.activeCameras.length > 0) {
  28149. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28150. if (cameraIndex > 0) {
  28151. this._engine.clear(null, false, true, true);
  28152. }
  28153. this._processSubCameras(this.activeCameras[cameraIndex]);
  28154. }
  28155. }
  28156. else {
  28157. if (!this.activeCamera) {
  28158. throw new Error("No camera defined");
  28159. }
  28160. this._processSubCameras(this.activeCamera);
  28161. }
  28162. // Intersection checks
  28163. this._checkIntersections();
  28164. // Update the audio listener attached to the camera
  28165. if (BABYLON.AudioEngine) {
  28166. this._updateAudioParameters();
  28167. }
  28168. // After render
  28169. if (this.afterRender) {
  28170. this.afterRender();
  28171. }
  28172. this.onAfterRenderObservable.notifyObservers(this);
  28173. // Cleaning
  28174. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28175. var data = this._toBeDisposed.data[index];
  28176. if (data) {
  28177. data.dispose();
  28178. }
  28179. this._toBeDisposed[index] = null;
  28180. }
  28181. this._toBeDisposed.reset();
  28182. if (this.dumpNextRenderTargets) {
  28183. this.dumpNextRenderTargets = false;
  28184. }
  28185. this._activeBones.addCount(0, true);
  28186. this._activeIndices.addCount(0, true);
  28187. this._activeParticles.addCount(0, true);
  28188. };
  28189. Scene.prototype._updateAudioParameters = function () {
  28190. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28191. return;
  28192. }
  28193. var listeningCamera;
  28194. var audioEngine = BABYLON.Engine.audioEngine;
  28195. if (this.activeCameras.length > 0) {
  28196. listeningCamera = this.activeCameras[0];
  28197. }
  28198. else {
  28199. listeningCamera = this.activeCamera;
  28200. }
  28201. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28202. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28203. // for VR cameras
  28204. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28205. listeningCamera = listeningCamera.rigCameras[0];
  28206. }
  28207. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28208. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28209. cameraDirection.normalize();
  28210. // To avoid some errors on GearVR
  28211. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28212. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28213. }
  28214. var i;
  28215. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28216. var sound = this.mainSoundTrack.soundCollection[i];
  28217. if (sound.useCustomAttenuation) {
  28218. sound.updateDistanceFromListener();
  28219. }
  28220. }
  28221. for (i = 0; i < this.soundTracks.length; i++) {
  28222. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28223. sound = this.soundTracks[i].soundCollection[j];
  28224. if (sound.useCustomAttenuation) {
  28225. sound.updateDistanceFromListener();
  28226. }
  28227. }
  28228. }
  28229. }
  28230. };
  28231. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28232. // Audio
  28233. /**
  28234. * Gets or sets if audio support is enabled
  28235. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28236. */
  28237. get: function () {
  28238. return this._audioEnabled;
  28239. },
  28240. set: function (value) {
  28241. this._audioEnabled = value;
  28242. if (BABYLON.AudioEngine) {
  28243. if (this._audioEnabled) {
  28244. this._enableAudio();
  28245. }
  28246. else {
  28247. this._disableAudio();
  28248. }
  28249. }
  28250. },
  28251. enumerable: true,
  28252. configurable: true
  28253. });
  28254. Scene.prototype._disableAudio = function () {
  28255. var i;
  28256. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28257. this.mainSoundTrack.soundCollection[i].pause();
  28258. }
  28259. for (i = 0; i < this.soundTracks.length; i++) {
  28260. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28261. this.soundTracks[i].soundCollection[j].pause();
  28262. }
  28263. }
  28264. };
  28265. Scene.prototype._enableAudio = function () {
  28266. var i;
  28267. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28268. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28269. this.mainSoundTrack.soundCollection[i].play();
  28270. }
  28271. }
  28272. for (i = 0; i < this.soundTracks.length; i++) {
  28273. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28274. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28275. this.soundTracks[i].soundCollection[j].play();
  28276. }
  28277. }
  28278. }
  28279. };
  28280. Object.defineProperty(Scene.prototype, "headphone", {
  28281. /**
  28282. * Gets or sets if audio will be output to headphones
  28283. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28284. */
  28285. get: function () {
  28286. return this._headphone;
  28287. },
  28288. set: function (value) {
  28289. this._headphone = value;
  28290. if (BABYLON.AudioEngine) {
  28291. if (this._headphone) {
  28292. this._switchAudioModeForHeadphones();
  28293. }
  28294. else {
  28295. this._switchAudioModeForNormalSpeakers();
  28296. }
  28297. }
  28298. },
  28299. enumerable: true,
  28300. configurable: true
  28301. });
  28302. Scene.prototype._switchAudioModeForHeadphones = function () {
  28303. this.mainSoundTrack.switchPanningModelToHRTF();
  28304. for (var i = 0; i < this.soundTracks.length; i++) {
  28305. this.soundTracks[i].switchPanningModelToHRTF();
  28306. }
  28307. };
  28308. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28309. this.mainSoundTrack.switchPanningModelToEqualPower();
  28310. for (var i = 0; i < this.soundTracks.length; i++) {
  28311. this.soundTracks[i].switchPanningModelToEqualPower();
  28312. }
  28313. };
  28314. /**
  28315. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28316. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28317. * @returns the created depth renderer
  28318. */
  28319. Scene.prototype.enableDepthRenderer = function (camera) {
  28320. camera = camera || this.activeCamera;
  28321. if (!camera) {
  28322. throw "No camera available to enable depth renderer";
  28323. }
  28324. if (!this._depthRenderer[camera.id]) {
  28325. var textureType = 0;
  28326. if (this._engine.getCaps().textureHalfFloatRender) {
  28327. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28328. }
  28329. else if (this._engine.getCaps().textureFloatRender) {
  28330. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28331. }
  28332. else {
  28333. throw "Depth renderer does not support int texture type";
  28334. }
  28335. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28336. }
  28337. return this._depthRenderer[camera.id];
  28338. };
  28339. /**
  28340. * Disables a depth renderer for a given camera
  28341. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28342. */
  28343. Scene.prototype.disableDepthRenderer = function (camera) {
  28344. camera = camera || this.activeCamera;
  28345. if (!camera || !this._depthRenderer[camera.id]) {
  28346. return;
  28347. }
  28348. this._depthRenderer[camera.id].dispose();
  28349. delete this._depthRenderer[camera.id];
  28350. };
  28351. /**
  28352. * Enables a GeometryBufferRender and associates it with the scene
  28353. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28354. * @returns the GeometryBufferRenderer
  28355. */
  28356. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28357. if (ratio === void 0) { ratio = 1; }
  28358. if (this._geometryBufferRenderer) {
  28359. return this._geometryBufferRenderer;
  28360. }
  28361. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28362. if (!this._geometryBufferRenderer.isSupported) {
  28363. this._geometryBufferRenderer = null;
  28364. }
  28365. return this._geometryBufferRenderer;
  28366. };
  28367. /**
  28368. * Disables the GeometryBufferRender associated with the scene
  28369. */
  28370. Scene.prototype.disableGeometryBufferRenderer = function () {
  28371. if (!this._geometryBufferRenderer) {
  28372. return;
  28373. }
  28374. this._geometryBufferRenderer.dispose();
  28375. this._geometryBufferRenderer = null;
  28376. };
  28377. /**
  28378. * Freeze all materials
  28379. * A frozen material will not be updatable but should be faster to render
  28380. */
  28381. Scene.prototype.freezeMaterials = function () {
  28382. for (var i = 0; i < this.materials.length; i++) {
  28383. this.materials[i].freeze();
  28384. }
  28385. };
  28386. /**
  28387. * Unfreeze all materials
  28388. * A frozen material will not be updatable but should be faster to render
  28389. */
  28390. Scene.prototype.unfreezeMaterials = function () {
  28391. for (var i = 0; i < this.materials.length; i++) {
  28392. this.materials[i].unfreeze();
  28393. }
  28394. };
  28395. /**
  28396. * Releases all held ressources
  28397. */
  28398. Scene.prototype.dispose = function () {
  28399. this.beforeRender = null;
  28400. this.afterRender = null;
  28401. this.skeletons = [];
  28402. this.morphTargetManagers = [];
  28403. this._transientComponents = [];
  28404. this._isReadyForMeshStage.clear();
  28405. this._cameraDrawRenderTargetStage.clear();
  28406. this._beforeCameraDrawStage.clear();
  28407. this._beforeRenderingGroupDrawStage.clear();
  28408. this._afterRenderingGroupDrawStage.clear();
  28409. this._afterCameraDrawStage.clear();
  28410. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28411. var component = _a[_i];
  28412. component.dispose();
  28413. }
  28414. this.importedMeshesFiles = new Array();
  28415. this.stopAllAnimations();
  28416. this.resetCachedMaterial();
  28417. for (var key in this._depthRenderer) {
  28418. this._depthRenderer[key].dispose();
  28419. }
  28420. if (this._gamepadManager) {
  28421. this._gamepadManager.dispose();
  28422. this._gamepadManager = null;
  28423. }
  28424. // Smart arrays
  28425. if (this.activeCamera) {
  28426. this.activeCamera._activeMeshes.dispose();
  28427. this.activeCamera = null;
  28428. }
  28429. this._activeMeshes.dispose();
  28430. this._renderingManager.dispose();
  28431. this._processedMaterials.dispose();
  28432. this._activeParticleSystems.dispose();
  28433. this._activeSkeletons.dispose();
  28434. this._softwareSkinnedMeshes.dispose();
  28435. this._renderTargets.dispose();
  28436. this._registeredForLateAnimationBindings.dispose();
  28437. if (this._boundingBoxRenderer) {
  28438. this._boundingBoxRenderer.dispose();
  28439. }
  28440. this._meshesForIntersections.dispose();
  28441. this._toBeDisposed.dispose();
  28442. // Abort active requests
  28443. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28444. var request = _c[_b];
  28445. request.abort();
  28446. }
  28447. // Debug layer
  28448. if (this._debugLayer) {
  28449. this._debugLayer.hide();
  28450. }
  28451. // Events
  28452. this.onDisposeObservable.notifyObservers(this);
  28453. this.onDisposeObservable.clear();
  28454. this.onBeforeRenderObservable.clear();
  28455. this.onAfterRenderObservable.clear();
  28456. this.onBeforeRenderTargetsRenderObservable.clear();
  28457. this.onAfterRenderTargetsRenderObservable.clear();
  28458. this.onAfterStepObservable.clear();
  28459. this.onBeforeStepObservable.clear();
  28460. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28461. this.onAfterActiveMeshesEvaluationObservable.clear();
  28462. this.onBeforeParticlesRenderingObservable.clear();
  28463. this.onAfterParticlesRenderingObservable.clear();
  28464. this.onBeforeSpritesRenderingObservable.clear();
  28465. this.onAfterSpritesRenderingObservable.clear();
  28466. this.onBeforeDrawPhaseObservable.clear();
  28467. this.onAfterDrawPhaseObservable.clear();
  28468. this.onBeforePhysicsObservable.clear();
  28469. this.onAfterPhysicsObservable.clear();
  28470. this.onBeforeAnimationsObservable.clear();
  28471. this.onAfterAnimationsObservable.clear();
  28472. this.onDataLoadedObservable.clear();
  28473. this.detachControl();
  28474. // Release sounds & sounds tracks
  28475. if (BABYLON.AudioEngine) {
  28476. this.disposeSounds();
  28477. }
  28478. // VR Helper
  28479. if (this.VRHelper) {
  28480. this.VRHelper.dispose();
  28481. }
  28482. // Detach cameras
  28483. var canvas = this._engine.getRenderingCanvas();
  28484. if (canvas) {
  28485. var index;
  28486. for (index = 0; index < this.cameras.length; index++) {
  28487. this.cameras[index].detachControl(canvas);
  28488. }
  28489. }
  28490. // Release animation groups
  28491. while (this.animationGroups.length) {
  28492. this.animationGroups[0].dispose();
  28493. }
  28494. // Release lights
  28495. while (this.lights.length) {
  28496. this.lights[0].dispose();
  28497. }
  28498. // Release meshes
  28499. while (this.meshes.length) {
  28500. this.meshes[0].dispose(true);
  28501. }
  28502. while (this.transformNodes.length) {
  28503. this.removeTransformNode(this.transformNodes[0]);
  28504. }
  28505. // Release cameras
  28506. while (this.cameras.length) {
  28507. this.cameras[0].dispose();
  28508. }
  28509. // Release materials
  28510. if (this.defaultMaterial) {
  28511. this.defaultMaterial.dispose();
  28512. }
  28513. while (this.multiMaterials.length) {
  28514. this.multiMaterials[0].dispose();
  28515. }
  28516. while (this.materials.length) {
  28517. this.materials[0].dispose();
  28518. }
  28519. // Release particles
  28520. while (this.particleSystems.length) {
  28521. this.particleSystems[0].dispose();
  28522. }
  28523. // Release sprites
  28524. while (this.spriteManagers.length) {
  28525. this.spriteManagers[0].dispose();
  28526. }
  28527. // Release postProcesses
  28528. while (this.postProcesses.length) {
  28529. this.postProcesses[0].dispose();
  28530. }
  28531. // Release textures
  28532. while (this.textures.length) {
  28533. this.textures[0].dispose();
  28534. }
  28535. // Release UBO
  28536. this._sceneUbo.dispose();
  28537. if (this._alternateSceneUbo) {
  28538. this._alternateSceneUbo.dispose();
  28539. }
  28540. // Post-processes
  28541. this.postProcessManager.dispose();
  28542. if (this._postProcessRenderPipelineManager) {
  28543. this._postProcessRenderPipelineManager.dispose();
  28544. }
  28545. // Physics
  28546. if (this._physicsEngine) {
  28547. this.disablePhysicsEngine();
  28548. }
  28549. // Remove from engine
  28550. index = this._engine.scenes.indexOf(this);
  28551. if (index > -1) {
  28552. this._engine.scenes.splice(index, 1);
  28553. }
  28554. this._engine.wipeCaches(true);
  28555. this._isDisposed = true;
  28556. };
  28557. Object.defineProperty(Scene.prototype, "isDisposed", {
  28558. /**
  28559. * Gets if the scene is already disposed
  28560. */
  28561. get: function () {
  28562. return this._isDisposed;
  28563. },
  28564. enumerable: true,
  28565. configurable: true
  28566. });
  28567. /**
  28568. * Releases sounds & soundtracks
  28569. */
  28570. Scene.prototype.disposeSounds = function () {
  28571. if (!this._mainSoundTrack) {
  28572. return;
  28573. }
  28574. this.mainSoundTrack.dispose();
  28575. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28576. this.soundTracks[scIndex].dispose();
  28577. }
  28578. };
  28579. /**
  28580. * Call this function to reduce memory footprint of the scene.
  28581. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28582. */
  28583. Scene.prototype.clearCachedVertexData = function () {
  28584. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28585. var mesh = this.meshes[meshIndex];
  28586. var geometry = mesh.geometry;
  28587. if (geometry) {
  28588. geometry._indices = [];
  28589. for (var vbName in geometry._vertexBuffers) {
  28590. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28591. continue;
  28592. }
  28593. geometry._vertexBuffers[vbName]._buffer._data = null;
  28594. }
  28595. }
  28596. }
  28597. };
  28598. /**
  28599. * This function will remove the local cached buffer data from texture.
  28600. * It will save memory but will prevent the texture from being rebuilt
  28601. */
  28602. Scene.prototype.cleanCachedTextureBuffer = function () {
  28603. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28604. var baseTexture = _a[_i];
  28605. var buffer = baseTexture._buffer;
  28606. if (buffer) {
  28607. baseTexture._buffer = null;
  28608. }
  28609. }
  28610. };
  28611. // Octrees
  28612. /**
  28613. * Get the world extend vectors with an optional filter
  28614. *
  28615. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28616. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28617. */
  28618. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28619. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28620. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28621. filterPredicate = filterPredicate || (function () { return true; });
  28622. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28623. mesh.computeWorldMatrix(true);
  28624. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28625. return;
  28626. }
  28627. var boundingInfo = mesh.getBoundingInfo();
  28628. var minBox = boundingInfo.boundingBox.minimumWorld;
  28629. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28630. BABYLON.Tools.CheckExtends(minBox, min, max);
  28631. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28632. });
  28633. return {
  28634. min: min,
  28635. max: max
  28636. };
  28637. };
  28638. /**
  28639. * Creates or updates the octree used to boost selection (picking)
  28640. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28641. * @param maxCapacity defines the maximum capacity per leaf
  28642. * @param maxDepth defines the maximum depth of the octree
  28643. * @returns an octree of AbstractMesh
  28644. */
  28645. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28646. if (maxCapacity === void 0) { maxCapacity = 64; }
  28647. if (maxDepth === void 0) { maxDepth = 2; }
  28648. if (!this._selectionOctree) {
  28649. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28650. }
  28651. var worldExtends = this.getWorldExtends();
  28652. // Update octree
  28653. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28654. return this._selectionOctree;
  28655. };
  28656. // Picking
  28657. /**
  28658. * Creates a ray that can be used to pick in the scene
  28659. * @param x defines the x coordinate of the origin (on-screen)
  28660. * @param y defines the y coordinate of the origin (on-screen)
  28661. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28662. * @param camera defines the camera to use for the picking
  28663. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28664. * @returns a Ray
  28665. */
  28666. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28667. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28668. var result = BABYLON.Ray.Zero();
  28669. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28670. return result;
  28671. };
  28672. /**
  28673. * Creates a ray that can be used to pick in the scene
  28674. * @param x defines the x coordinate of the origin (on-screen)
  28675. * @param y defines the y coordinate of the origin (on-screen)
  28676. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28677. * @param result defines the ray where to store the picking ray
  28678. * @param camera defines the camera to use for the picking
  28679. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28680. * @returns the current scene
  28681. */
  28682. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28683. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28684. var engine = this._engine;
  28685. if (!camera) {
  28686. if (!this.activeCamera)
  28687. throw new Error("Active camera not set");
  28688. camera = this.activeCamera;
  28689. }
  28690. var cameraViewport = camera.viewport;
  28691. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28692. // Moving coordinates to local viewport world
  28693. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28694. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28695. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28696. return this;
  28697. };
  28698. /**
  28699. * Creates a ray that can be used to pick in the scene
  28700. * @param x defines the x coordinate of the origin (on-screen)
  28701. * @param y defines the y coordinate of the origin (on-screen)
  28702. * @param camera defines the camera to use for the picking
  28703. * @returns a Ray
  28704. */
  28705. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28706. var result = BABYLON.Ray.Zero();
  28707. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28708. return result;
  28709. };
  28710. /**
  28711. * Creates a ray that can be used to pick in the scene
  28712. * @param x defines the x coordinate of the origin (on-screen)
  28713. * @param y defines the y coordinate of the origin (on-screen)
  28714. * @param result defines the ray where to store the picking ray
  28715. * @param camera defines the camera to use for the picking
  28716. * @returns the current scene
  28717. */
  28718. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28719. if (!BABYLON.PickingInfo) {
  28720. return this;
  28721. }
  28722. var engine = this._engine;
  28723. if (!camera) {
  28724. if (!this.activeCamera)
  28725. throw new Error("Active camera not set");
  28726. camera = this.activeCamera;
  28727. }
  28728. var cameraViewport = camera.viewport;
  28729. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28730. var identity = BABYLON.Matrix.Identity();
  28731. // Moving coordinates to local viewport world
  28732. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28733. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28734. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28735. return this;
  28736. };
  28737. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28738. if (!BABYLON.PickingInfo) {
  28739. return null;
  28740. }
  28741. var pickingInfo = null;
  28742. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28743. var mesh = this.meshes[meshIndex];
  28744. if (predicate) {
  28745. if (!predicate(mesh)) {
  28746. continue;
  28747. }
  28748. }
  28749. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28750. continue;
  28751. }
  28752. var world = mesh.getWorldMatrix();
  28753. var ray = rayFunction(world);
  28754. var result = mesh.intersects(ray, fastCheck);
  28755. if (!result || !result.hit)
  28756. continue;
  28757. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28758. continue;
  28759. pickingInfo = result;
  28760. if (fastCheck) {
  28761. break;
  28762. }
  28763. }
  28764. return pickingInfo || new BABYLON.PickingInfo();
  28765. };
  28766. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28767. if (!BABYLON.PickingInfo) {
  28768. return null;
  28769. }
  28770. var pickingInfos = new Array();
  28771. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28772. var mesh = this.meshes[meshIndex];
  28773. if (predicate) {
  28774. if (!predicate(mesh)) {
  28775. continue;
  28776. }
  28777. }
  28778. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28779. continue;
  28780. }
  28781. var world = mesh.getWorldMatrix();
  28782. var ray = rayFunction(world);
  28783. var result = mesh.intersects(ray, false);
  28784. if (!result || !result.hit)
  28785. continue;
  28786. pickingInfos.push(result);
  28787. }
  28788. return pickingInfos;
  28789. };
  28790. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28791. if (!BABYLON.PickingInfo) {
  28792. return null;
  28793. }
  28794. var pickingInfo = null;
  28795. if (!camera) {
  28796. if (!this.activeCamera) {
  28797. return null;
  28798. }
  28799. camera = this.activeCamera;
  28800. }
  28801. if (this.spriteManagers.length > 0) {
  28802. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28803. var spriteManager = this.spriteManagers[spriteIndex];
  28804. if (!spriteManager.isPickable) {
  28805. continue;
  28806. }
  28807. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28808. if (!result || !result.hit)
  28809. continue;
  28810. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28811. continue;
  28812. pickingInfo = result;
  28813. if (fastCheck) {
  28814. break;
  28815. }
  28816. }
  28817. }
  28818. return pickingInfo || new BABYLON.PickingInfo();
  28819. };
  28820. /** Launch a ray to try to pick a mesh in the scene
  28821. * @param x position on screen
  28822. * @param y position on screen
  28823. * @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
  28824. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28825. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28826. * @returns a PickingInfo
  28827. */
  28828. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28829. var _this = this;
  28830. if (!BABYLON.PickingInfo) {
  28831. return null;
  28832. }
  28833. var result = this._internalPick(function (world) {
  28834. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28835. return _this._tempPickingRay;
  28836. }, predicate, fastCheck);
  28837. if (result) {
  28838. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28839. }
  28840. return result;
  28841. };
  28842. /** Launch a ray to try to pick a sprite in the scene
  28843. * @param x position on screen
  28844. * @param y position on screen
  28845. * @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
  28846. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28847. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28848. * @returns a PickingInfo
  28849. */
  28850. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28851. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28852. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28853. };
  28854. /** Use the given ray to pick a mesh in the scene
  28855. * @param ray The ray to use to pick meshes
  28856. * @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
  28857. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28858. * @returns a PickingInfo
  28859. */
  28860. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28861. var _this = this;
  28862. var result = this._internalPick(function (world) {
  28863. if (!_this._pickWithRayInverseMatrix) {
  28864. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28865. }
  28866. world.invertToRef(_this._pickWithRayInverseMatrix);
  28867. if (!_this._cachedRayForTransform) {
  28868. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28869. }
  28870. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28871. return _this._cachedRayForTransform;
  28872. }, predicate, fastCheck);
  28873. if (result) {
  28874. result.ray = ray;
  28875. }
  28876. return result;
  28877. };
  28878. /**
  28879. * Launch a ray to try to pick a mesh in the scene
  28880. * @param x X position on screen
  28881. * @param y Y position on screen
  28882. * @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
  28883. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28884. * @returns an array of PickingInfo
  28885. */
  28886. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28887. var _this = this;
  28888. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28889. };
  28890. /**
  28891. * Launch a ray to try to pick a mesh in the scene
  28892. * @param ray Ray to use
  28893. * @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
  28894. * @returns an array of PickingInfo
  28895. */
  28896. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28897. var _this = this;
  28898. return this._internalMultiPick(function (world) {
  28899. if (!_this._pickWithRayInverseMatrix) {
  28900. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28901. }
  28902. world.invertToRef(_this._pickWithRayInverseMatrix);
  28903. if (!_this._cachedRayForTransform) {
  28904. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28905. }
  28906. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28907. return _this._cachedRayForTransform;
  28908. }, predicate);
  28909. };
  28910. /**
  28911. * Force the value of meshUnderPointer
  28912. * @param mesh defines the mesh to use
  28913. */
  28914. Scene.prototype.setPointerOverMesh = function (mesh) {
  28915. if (this._pointerOverMesh === mesh) {
  28916. return;
  28917. }
  28918. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28919. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28920. }
  28921. this._pointerOverMesh = mesh;
  28922. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28923. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28924. }
  28925. };
  28926. /**
  28927. * Gets the mesh under the pointer
  28928. * @returns a Mesh or null if no mesh is under the pointer
  28929. */
  28930. Scene.prototype.getPointerOverMesh = function () {
  28931. return this._pointerOverMesh;
  28932. };
  28933. /**
  28934. * Force the sprite under the pointer
  28935. * @param sprite defines the sprite to use
  28936. */
  28937. Scene.prototype.setPointerOverSprite = function (sprite) {
  28938. if (this._pointerOverSprite === sprite) {
  28939. return;
  28940. }
  28941. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28942. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28943. }
  28944. this._pointerOverSprite = sprite;
  28945. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28946. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28947. }
  28948. };
  28949. /**
  28950. * Gets the sprite under the pointer
  28951. * @returns a Sprite or null if no sprite is under the pointer
  28952. */
  28953. Scene.prototype.getPointerOverSprite = function () {
  28954. return this._pointerOverSprite;
  28955. };
  28956. // Physics
  28957. /**
  28958. * Gets the current physics engine
  28959. * @returns a PhysicsEngine or null if none attached
  28960. */
  28961. Scene.prototype.getPhysicsEngine = function () {
  28962. return this._physicsEngine;
  28963. };
  28964. /**
  28965. * Enables physics to the current scene
  28966. * @param gravity defines the scene's gravity for the physics engine
  28967. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28968. * @return a boolean indicating if the physics engine was initialized
  28969. */
  28970. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28971. if (gravity === void 0) { gravity = null; }
  28972. if (this._physicsEngine) {
  28973. return true;
  28974. }
  28975. try {
  28976. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28977. return true;
  28978. }
  28979. catch (e) {
  28980. BABYLON.Tools.Error(e.message);
  28981. return false;
  28982. }
  28983. };
  28984. /**
  28985. * Disables and disposes the physics engine associated with the scene
  28986. */
  28987. Scene.prototype.disablePhysicsEngine = function () {
  28988. if (!this._physicsEngine) {
  28989. return;
  28990. }
  28991. this._physicsEngine.dispose();
  28992. this._physicsEngine = null;
  28993. };
  28994. /**
  28995. * Gets a boolean indicating if there is an active physics engine
  28996. * @returns a boolean indicating if there is an active physics engine
  28997. */
  28998. Scene.prototype.isPhysicsEnabled = function () {
  28999. return this._physicsEngine !== undefined;
  29000. };
  29001. /**
  29002. * Deletes a physics compound impostor
  29003. * @param compound defines the compound to delete
  29004. */
  29005. Scene.prototype.deleteCompoundImpostor = function (compound) {
  29006. var mesh = compound.parts[0].mesh;
  29007. if (mesh.physicsImpostor) {
  29008. mesh.physicsImpostor.dispose( /*true*/);
  29009. mesh.physicsImpostor = null;
  29010. }
  29011. };
  29012. // Misc.
  29013. /** @hidden */
  29014. Scene.prototype._rebuildGeometries = function () {
  29015. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29016. var geometry = _a[_i];
  29017. geometry._rebuild();
  29018. }
  29019. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29020. var mesh = _c[_b];
  29021. mesh._rebuild();
  29022. }
  29023. if (this.postProcessManager) {
  29024. this.postProcessManager._rebuild();
  29025. }
  29026. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29027. var component = _e[_d];
  29028. component.rebuild();
  29029. }
  29030. if (this._boundingBoxRenderer) {
  29031. this._boundingBoxRenderer._rebuild();
  29032. }
  29033. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29034. var system = _g[_f];
  29035. system.rebuild();
  29036. }
  29037. if (this._postProcessRenderPipelineManager) {
  29038. this._postProcessRenderPipelineManager._rebuild();
  29039. }
  29040. };
  29041. /** @hidden */
  29042. Scene.prototype._rebuildTextures = function () {
  29043. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29044. var texture = _a[_i];
  29045. texture._rebuild();
  29046. }
  29047. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29048. };
  29049. /**
  29050. * Creates a default light for the scene.
  29051. * @param replace Whether to replace the existing lights in the scene.
  29052. */
  29053. Scene.prototype.createDefaultLight = function (replace) {
  29054. if (replace === void 0) { replace = false; }
  29055. // Dispose existing light in replace mode.
  29056. if (replace) {
  29057. if (this.lights) {
  29058. for (var i = 0; i < this.lights.length; i++) {
  29059. this.lights[i].dispose();
  29060. }
  29061. }
  29062. }
  29063. // Light
  29064. if (this.lights.length === 0) {
  29065. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29066. }
  29067. };
  29068. /**
  29069. * Creates a default camera for the scene.
  29070. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29071. * @param replace Whether to replace the existing active camera in the scene.
  29072. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29073. */
  29074. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29075. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29076. if (replace === void 0) { replace = false; }
  29077. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29078. // Dispose existing camera in replace mode.
  29079. if (replace) {
  29080. if (this.activeCamera) {
  29081. this.activeCamera.dispose();
  29082. this.activeCamera = null;
  29083. }
  29084. }
  29085. // Camera
  29086. if (!this.activeCamera) {
  29087. var worldExtends = this.getWorldExtends();
  29088. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29089. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29090. var camera;
  29091. var radius = worldSize.length() * 1.5;
  29092. // empty scene scenario!
  29093. if (!isFinite(radius)) {
  29094. radius = 1;
  29095. worldCenter.copyFromFloats(0, 0, 0);
  29096. }
  29097. if (createArcRotateCamera) {
  29098. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29099. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29100. arcRotateCamera.wheelPrecision = 100 / radius;
  29101. camera = arcRotateCamera;
  29102. }
  29103. else {
  29104. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29105. freeCamera.setTarget(worldCenter);
  29106. camera = freeCamera;
  29107. }
  29108. camera.minZ = radius * 0.01;
  29109. camera.maxZ = radius * 1000;
  29110. camera.speed = radius * 0.2;
  29111. this.activeCamera = camera;
  29112. var canvas = this.getEngine().getRenderingCanvas();
  29113. if (attachCameraControls && canvas) {
  29114. camera.attachControl(canvas);
  29115. }
  29116. }
  29117. };
  29118. /**
  29119. * Creates a default camera and a default light
  29120. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29121. * @param replace defines if the camera and/or light will replace the existing ones
  29122. * @param attachCameraControls defines if attachControl will be called on the new camera
  29123. */
  29124. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29125. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29126. if (replace === void 0) { replace = false; }
  29127. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29128. this.createDefaultLight(replace);
  29129. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29130. };
  29131. /**
  29132. * Creates a new sky box
  29133. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29134. * @param environmentTexture defines the texture to use as environment texture
  29135. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29136. * @param scale defines the overall scale of the skybox
  29137. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29138. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29139. * @returns a new mesh holding the sky box
  29140. */
  29141. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29142. if (pbr === void 0) { pbr = false; }
  29143. if (scale === void 0) { scale = 1000; }
  29144. if (blur === void 0) { blur = 0; }
  29145. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29146. if (!environmentTexture) {
  29147. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29148. return null;
  29149. }
  29150. if (setGlobalEnvTexture) {
  29151. if (environmentTexture) {
  29152. this.environmentTexture = environmentTexture;
  29153. }
  29154. }
  29155. // Skybox
  29156. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29157. if (pbr) {
  29158. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29159. hdrSkyboxMaterial.backFaceCulling = false;
  29160. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29161. if (hdrSkyboxMaterial.reflectionTexture) {
  29162. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29163. }
  29164. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29165. hdrSkyboxMaterial.disableLighting = true;
  29166. hdrSkyboxMaterial.twoSidedLighting = true;
  29167. hdrSkybox.infiniteDistance = true;
  29168. hdrSkybox.material = hdrSkyboxMaterial;
  29169. }
  29170. else {
  29171. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29172. skyboxMaterial.backFaceCulling = false;
  29173. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29174. if (skyboxMaterial.reflectionTexture) {
  29175. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29176. }
  29177. skyboxMaterial.disableLighting = true;
  29178. hdrSkybox.infiniteDistance = true;
  29179. hdrSkybox.material = skyboxMaterial;
  29180. }
  29181. return hdrSkybox;
  29182. };
  29183. /**
  29184. * Creates a new environment
  29185. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29186. * @param options defines the options you can use to configure the environment
  29187. * @returns the new EnvironmentHelper
  29188. */
  29189. Scene.prototype.createDefaultEnvironment = function (options) {
  29190. if (BABYLON.EnvironmentHelper) {
  29191. return new BABYLON.EnvironmentHelper(options, this);
  29192. }
  29193. return null;
  29194. };
  29195. /**
  29196. * Creates a new VREXperienceHelper
  29197. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29198. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29199. * @returns a new VREXperienceHelper
  29200. */
  29201. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29202. if (webVROptions === void 0) { webVROptions = {}; }
  29203. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29204. };
  29205. // Tags
  29206. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29207. if (tagsQuery === undefined) {
  29208. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29209. return list;
  29210. }
  29211. var listByTags = [];
  29212. forEach = forEach || (function (item) { return; });
  29213. for (var i in list) {
  29214. var item = list[i];
  29215. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29216. listByTags.push(item);
  29217. forEach(item);
  29218. }
  29219. }
  29220. return listByTags;
  29221. };
  29222. /**
  29223. * Get a list of meshes by tags
  29224. * @param tagsQuery defines the tags query to use
  29225. * @param forEach defines a predicate used to filter results
  29226. * @returns an array of Mesh
  29227. */
  29228. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29229. return this._getByTags(this.meshes, tagsQuery, forEach);
  29230. };
  29231. /**
  29232. * Get a list of cameras by tags
  29233. * @param tagsQuery defines the tags query to use
  29234. * @param forEach defines a predicate used to filter results
  29235. * @returns an array of Camera
  29236. */
  29237. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29238. return this._getByTags(this.cameras, tagsQuery, forEach);
  29239. };
  29240. /**
  29241. * Get a list of lights by tags
  29242. * @param tagsQuery defines the tags query to use
  29243. * @param forEach defines a predicate used to filter results
  29244. * @returns an array of Light
  29245. */
  29246. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29247. return this._getByTags(this.lights, tagsQuery, forEach);
  29248. };
  29249. /**
  29250. * Get a list of materials by tags
  29251. * @param tagsQuery defines the tags query to use
  29252. * @param forEach defines a predicate used to filter results
  29253. * @returns an array of Material
  29254. */
  29255. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29256. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29257. };
  29258. /**
  29259. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29260. * This allowed control for front to back rendering or reversly depending of the special needs.
  29261. *
  29262. * @param renderingGroupId The rendering group id corresponding to its index
  29263. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29264. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29265. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29266. */
  29267. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29268. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29269. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29270. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29271. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29272. };
  29273. /**
  29274. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29275. *
  29276. * @param renderingGroupId The rendering group id corresponding to its index
  29277. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29278. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29279. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29280. */
  29281. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29282. if (depth === void 0) { depth = true; }
  29283. if (stencil === void 0) { stencil = true; }
  29284. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29285. };
  29286. /**
  29287. * Will flag all materials as dirty to trigger new shader compilation
  29288. * @param flag defines the flag used to specify which material part must be marked as dirty
  29289. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29290. */
  29291. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29292. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29293. var material = _a[_i];
  29294. if (predicate && !predicate(material)) {
  29295. continue;
  29296. }
  29297. material.markAsDirty(flag);
  29298. }
  29299. };
  29300. /** @hidden */
  29301. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29302. var _this = this;
  29303. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29304. this._activeRequests.push(request);
  29305. request.onCompleteObservable.add(function (request) {
  29306. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29307. });
  29308. return request;
  29309. };
  29310. /** @hidden */
  29311. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29312. var _this = this;
  29313. return new Promise(function (resolve, reject) {
  29314. _this._loadFile(url, function (data) {
  29315. resolve(data);
  29316. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29317. reject(exception);
  29318. });
  29319. });
  29320. };
  29321. // Statics
  29322. Scene._FOGMODE_NONE = 0;
  29323. Scene._FOGMODE_EXP = 1;
  29324. Scene._FOGMODE_EXP2 = 2;
  29325. Scene._FOGMODE_LINEAR = 3;
  29326. Scene._uniqueIdCounter = 0;
  29327. /**
  29328. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29329. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29330. */
  29331. Scene.MinDeltaTime = 1.0;
  29332. /**
  29333. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29334. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29335. */
  29336. Scene.MaxDeltaTime = 1000.0;
  29337. /** The distance in pixel that you have to move to prevent some events */
  29338. Scene.DragMovementThreshold = 10; // in pixels
  29339. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29340. Scene.LongPressDelay = 500; // in milliseconds
  29341. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29342. Scene.DoubleClickDelay = 300; // in milliseconds
  29343. /** If you need to check double click without raising a single click at first click, enable this flag */
  29344. Scene.ExclusiveDoubleClickMode = false;
  29345. return Scene;
  29346. }(BABYLON.AbstractScene));
  29347. BABYLON.Scene = Scene;
  29348. })(BABYLON || (BABYLON = {}));
  29349. //# sourceMappingURL=babylon.scene.js.map
  29350. var BABYLON;
  29351. (function (BABYLON) {
  29352. /**
  29353. * Set of assets to keep when moving a scene into an asset container.
  29354. */
  29355. var KeepAssets = /** @class */ (function (_super) {
  29356. __extends(KeepAssets, _super);
  29357. function KeepAssets() {
  29358. return _super !== null && _super.apply(this, arguments) || this;
  29359. }
  29360. return KeepAssets;
  29361. }(BABYLON.AbstractScene));
  29362. BABYLON.KeepAssets = KeepAssets;
  29363. /**
  29364. * Container with a set of assets that can be added or removed from a scene.
  29365. */
  29366. var AssetContainer = /** @class */ (function (_super) {
  29367. __extends(AssetContainer, _super);
  29368. /**
  29369. * Instantiates an AssetContainer.
  29370. * @param scene The scene the AssetContainer belongs to.
  29371. */
  29372. function AssetContainer(scene) {
  29373. var _this = _super.call(this) || this;
  29374. _this.scene = scene;
  29375. return _this;
  29376. }
  29377. /**
  29378. * Adds all the assets from the container to the scene.
  29379. */
  29380. AssetContainer.prototype.addAllToScene = function () {
  29381. var _this = this;
  29382. this.cameras.forEach(function (o) {
  29383. _this.scene.addCamera(o);
  29384. });
  29385. this.lights.forEach(function (o) {
  29386. _this.scene.addLight(o);
  29387. });
  29388. this.meshes.forEach(function (o) {
  29389. _this.scene.addMesh(o);
  29390. });
  29391. this.skeletons.forEach(function (o) {
  29392. _this.scene.addSkeleton(o);
  29393. });
  29394. this.particleSystems.forEach(function (o) {
  29395. _this.scene.addParticleSystem(o);
  29396. });
  29397. this.animations.forEach(function (o) {
  29398. _this.scene.addAnimation(o);
  29399. });
  29400. this.animationGroups.forEach(function (o) {
  29401. _this.scene.addAnimationGroup(o);
  29402. });
  29403. this.multiMaterials.forEach(function (o) {
  29404. _this.scene.addMultiMaterial(o);
  29405. });
  29406. this.materials.forEach(function (o) {
  29407. _this.scene.addMaterial(o);
  29408. });
  29409. this.morphTargetManagers.forEach(function (o) {
  29410. _this.scene.addMorphTargetManager(o);
  29411. });
  29412. this.geometries.forEach(function (o) {
  29413. _this.scene.addGeometry(o);
  29414. });
  29415. this.transformNodes.forEach(function (o) {
  29416. _this.scene.addTransformNode(o);
  29417. });
  29418. this.actionManagers.forEach(function (o) {
  29419. _this.scene.addActionManager(o);
  29420. });
  29421. this.sounds.forEach(function (o) {
  29422. o.play();
  29423. o.autoplay = true;
  29424. _this.scene.mainSoundTrack.AddSound(o);
  29425. });
  29426. this.textures.forEach(function (o) {
  29427. _this.scene.addTexture(o);
  29428. });
  29429. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29430. var component = _a[_i];
  29431. component.addFromContainer(this.scene);
  29432. }
  29433. };
  29434. /**
  29435. * Removes all the assets in the container from the scene
  29436. */
  29437. AssetContainer.prototype.removeAllFromScene = function () {
  29438. var _this = this;
  29439. this.cameras.forEach(function (o) {
  29440. _this.scene.removeCamera(o);
  29441. });
  29442. this.lights.forEach(function (o) {
  29443. _this.scene.removeLight(o);
  29444. });
  29445. this.meshes.forEach(function (o) {
  29446. _this.scene.removeMesh(o);
  29447. });
  29448. this.skeletons.forEach(function (o) {
  29449. _this.scene.removeSkeleton(o);
  29450. });
  29451. this.particleSystems.forEach(function (o) {
  29452. _this.scene.removeParticleSystem(o);
  29453. });
  29454. this.animations.forEach(function (o) {
  29455. _this.scene.removeAnimation(o);
  29456. });
  29457. this.animationGroups.forEach(function (o) {
  29458. _this.scene.removeAnimationGroup(o);
  29459. });
  29460. this.multiMaterials.forEach(function (o) {
  29461. _this.scene.removeMultiMaterial(o);
  29462. });
  29463. this.materials.forEach(function (o) {
  29464. _this.scene.removeMaterial(o);
  29465. });
  29466. this.morphTargetManagers.forEach(function (o) {
  29467. _this.scene.removeMorphTargetManager(o);
  29468. });
  29469. this.geometries.forEach(function (o) {
  29470. _this.scene.removeGeometry(o);
  29471. });
  29472. this.transformNodes.forEach(function (o) {
  29473. _this.scene.removeTransformNode(o);
  29474. });
  29475. this.actionManagers.forEach(function (o) {
  29476. _this.scene.removeActionManager(o);
  29477. });
  29478. this.sounds.forEach(function (o) {
  29479. o.stop();
  29480. o.autoplay = false;
  29481. _this.scene.mainSoundTrack.RemoveSound(o);
  29482. });
  29483. this.textures.forEach(function (o) {
  29484. _this.scene.removeTexture(o);
  29485. });
  29486. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29487. var component = _a[_i];
  29488. component.removeFromContainer(this.scene);
  29489. }
  29490. };
  29491. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29492. if (!sourceAssets) {
  29493. return;
  29494. }
  29495. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29496. var asset = sourceAssets_1[_i];
  29497. var move = true;
  29498. if (keepAssets) {
  29499. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29500. var keepAsset = keepAssets_1[_a];
  29501. if (asset === keepAsset) {
  29502. move = false;
  29503. break;
  29504. }
  29505. }
  29506. }
  29507. if (move) {
  29508. targetAssets.push(asset);
  29509. }
  29510. }
  29511. };
  29512. /**
  29513. * Removes all the assets contained in the scene and adds them to the container.
  29514. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29515. */
  29516. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29517. if (keepAssets === undefined) {
  29518. keepAssets = new KeepAssets();
  29519. }
  29520. for (var key in this) {
  29521. if (this.hasOwnProperty(key)) {
  29522. this[key] = this[key] || [];
  29523. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29524. }
  29525. }
  29526. this.removeAllFromScene();
  29527. };
  29528. /**
  29529. * 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.
  29530. * @returns the root mesh
  29531. */
  29532. AssetContainer.prototype.createRootMesh = function () {
  29533. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29534. this.meshes.forEach(function (m) {
  29535. if (!m.parent) {
  29536. rootMesh.addChild(m);
  29537. }
  29538. });
  29539. this.meshes.unshift(rootMesh);
  29540. return rootMesh;
  29541. };
  29542. return AssetContainer;
  29543. }(BABYLON.AbstractScene));
  29544. BABYLON.AssetContainer = AssetContainer;
  29545. })(BABYLON || (BABYLON = {}));
  29546. //# sourceMappingURL=babylon.assetContainer.js.map
  29547. var BABYLON;
  29548. (function (BABYLON) {
  29549. var Buffer = /** @class */ (function () {
  29550. /**
  29551. * Constructor
  29552. * @param engine the engine
  29553. * @param data the data to use for this buffer
  29554. * @param updatable whether the data is updatable
  29555. * @param stride the stride (optional)
  29556. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29557. * @param instanced whether the buffer is instanced (optional)
  29558. * @param useBytes set to true if the stride in in bytes (optional)
  29559. */
  29560. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29561. if (stride === void 0) { stride = 0; }
  29562. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29563. if (instanced === void 0) { instanced = false; }
  29564. if (useBytes === void 0) { useBytes = false; }
  29565. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29566. this._engine = engine.getScene().getEngine();
  29567. }
  29568. else {
  29569. this._engine = engine;
  29570. }
  29571. this._updatable = updatable;
  29572. this._instanced = instanced;
  29573. this._data = data;
  29574. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29575. if (!postponeInternalCreation) { // by default
  29576. this.create();
  29577. }
  29578. }
  29579. /**
  29580. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29581. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29582. * @param offset defines offset in the buffer (0 by default)
  29583. * @param size defines the size in floats of attributes (position is 3 for instance)
  29584. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29585. * @param instanced defines if the vertex buffer contains indexed data
  29586. * @param useBytes defines if the offset and stride are in bytes
  29587. * @returns the new vertex buffer
  29588. */
  29589. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29590. if (useBytes === void 0) { useBytes = false; }
  29591. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29592. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29593. // a lot of these parameters are ignored as they are overriden by the buffer
  29594. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29595. };
  29596. // Properties
  29597. Buffer.prototype.isUpdatable = function () {
  29598. return this._updatable;
  29599. };
  29600. Buffer.prototype.getData = function () {
  29601. return this._data;
  29602. };
  29603. Buffer.prototype.getBuffer = function () {
  29604. return this._buffer;
  29605. };
  29606. /**
  29607. * Gets the stride in float32 units (i.e. byte stride / 4).
  29608. * May not be an integer if the byte stride is not divisible by 4.
  29609. * DEPRECATED. Use byteStride instead.
  29610. * @returns the stride in float32 units
  29611. */
  29612. Buffer.prototype.getStrideSize = function () {
  29613. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29614. };
  29615. // Methods
  29616. Buffer.prototype.create = function (data) {
  29617. if (data === void 0) { data = null; }
  29618. if (!data && this._buffer) {
  29619. return; // nothing to do
  29620. }
  29621. data = data || this._data;
  29622. if (!data) {
  29623. return;
  29624. }
  29625. if (!this._buffer) { // create buffer
  29626. if (this._updatable) {
  29627. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29628. this._data = data;
  29629. }
  29630. else {
  29631. this._buffer = this._engine.createVertexBuffer(data);
  29632. }
  29633. }
  29634. else if (this._updatable) { // update buffer
  29635. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29636. this._data = data;
  29637. }
  29638. };
  29639. Buffer.prototype._rebuild = function () {
  29640. this._buffer = null;
  29641. this.create(this._data);
  29642. };
  29643. Buffer.prototype.update = function (data) {
  29644. this.create(data);
  29645. };
  29646. /**
  29647. * Updates the data directly.
  29648. * @param data the new data
  29649. * @param offset the new offset
  29650. * @param vertexCount the vertex count (optional)
  29651. * @param useBytes set to true if the offset is in bytes
  29652. */
  29653. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29654. if (useBytes === void 0) { useBytes = false; }
  29655. if (!this._buffer) {
  29656. return;
  29657. }
  29658. if (this._updatable) { // update buffer
  29659. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29660. this._data = null;
  29661. }
  29662. };
  29663. Buffer.prototype.dispose = function () {
  29664. if (!this._buffer) {
  29665. return;
  29666. }
  29667. if (this._engine._releaseBuffer(this._buffer)) {
  29668. this._buffer = null;
  29669. }
  29670. };
  29671. return Buffer;
  29672. }());
  29673. BABYLON.Buffer = Buffer;
  29674. })(BABYLON || (BABYLON = {}));
  29675. //# sourceMappingURL=babylon.buffer.js.map
  29676. var BABYLON;
  29677. (function (BABYLON) {
  29678. var VertexBuffer = /** @class */ (function () {
  29679. /**
  29680. * Constructor
  29681. * @param engine the engine
  29682. * @param data the data to use for this vertex buffer
  29683. * @param kind the vertex buffer kind
  29684. * @param updatable whether the data is updatable
  29685. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29686. * @param stride the stride (optional)
  29687. * @param instanced whether the buffer is instanced (optional)
  29688. * @param offset the offset of the data (optional)
  29689. * @param size the number of components (optional)
  29690. * @param type the type of the component (optional)
  29691. * @param normalized whether the data contains normalized data (optional)
  29692. * @param useBytes set to true if stride and offset are in bytes (optional)
  29693. */
  29694. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29695. if (normalized === void 0) { normalized = false; }
  29696. if (useBytes === void 0) { useBytes = false; }
  29697. if (data instanceof BABYLON.Buffer) {
  29698. this._buffer = data;
  29699. this._ownsBuffer = false;
  29700. }
  29701. else {
  29702. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29703. this._ownsBuffer = true;
  29704. }
  29705. this._kind = kind;
  29706. if (type == undefined) {
  29707. var data_1 = this.getData();
  29708. this.type = VertexBuffer.FLOAT;
  29709. if (data_1 instanceof Int8Array)
  29710. this.type = VertexBuffer.BYTE;
  29711. else if (data_1 instanceof Uint8Array)
  29712. this.type = VertexBuffer.UNSIGNED_BYTE;
  29713. else if (data_1 instanceof Int16Array)
  29714. this.type = VertexBuffer.SHORT;
  29715. else if (data_1 instanceof Uint16Array)
  29716. this.type = VertexBuffer.UNSIGNED_SHORT;
  29717. else if (data_1 instanceof Int32Array)
  29718. this.type = VertexBuffer.INT;
  29719. else if (data_1 instanceof Uint32Array)
  29720. this.type = VertexBuffer.UNSIGNED_INT;
  29721. }
  29722. else {
  29723. this.type = type;
  29724. }
  29725. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29726. if (useBytes) {
  29727. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29728. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29729. this.byteOffset = offset || 0;
  29730. }
  29731. else {
  29732. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29733. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29734. this.byteOffset = (offset || 0) * typeByteLength;
  29735. }
  29736. this.normalized = normalized;
  29737. this._instanced = instanced !== undefined ? instanced : false;
  29738. this._instanceDivisor = instanced ? 1 : 0;
  29739. }
  29740. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29741. /**
  29742. * Gets or sets the instance divisor when in instanced mode
  29743. */
  29744. get: function () {
  29745. return this._instanceDivisor;
  29746. },
  29747. set: function (value) {
  29748. this._instanceDivisor = value;
  29749. if (value == 0) {
  29750. this._instanced = false;
  29751. }
  29752. else {
  29753. this._instanced = true;
  29754. }
  29755. },
  29756. enumerable: true,
  29757. configurable: true
  29758. });
  29759. VertexBuffer.prototype._rebuild = function () {
  29760. if (!this._buffer) {
  29761. return;
  29762. }
  29763. this._buffer._rebuild();
  29764. };
  29765. /**
  29766. * Returns the kind of the VertexBuffer (string).
  29767. */
  29768. VertexBuffer.prototype.getKind = function () {
  29769. return this._kind;
  29770. };
  29771. // Properties
  29772. /**
  29773. * Boolean : is the VertexBuffer updatable ?
  29774. */
  29775. VertexBuffer.prototype.isUpdatable = function () {
  29776. return this._buffer.isUpdatable();
  29777. };
  29778. /**
  29779. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29780. */
  29781. VertexBuffer.prototype.getData = function () {
  29782. return this._buffer.getData();
  29783. };
  29784. /**
  29785. * Returns the WebGLBuffer associated to the VertexBuffer.
  29786. */
  29787. VertexBuffer.prototype.getBuffer = function () {
  29788. return this._buffer.getBuffer();
  29789. };
  29790. /**
  29791. * Returns the stride as a multiple of the type byte length.
  29792. * DEPRECATED. Use byteStride instead.
  29793. */
  29794. VertexBuffer.prototype.getStrideSize = function () {
  29795. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29796. };
  29797. /**
  29798. * Returns the offset as a multiple of the type byte length.
  29799. * DEPRECATED. Use byteOffset instead.
  29800. */
  29801. VertexBuffer.prototype.getOffset = function () {
  29802. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29803. };
  29804. /**
  29805. * Returns the number of components per vertex attribute (integer).
  29806. */
  29807. VertexBuffer.prototype.getSize = function () {
  29808. return this._size;
  29809. };
  29810. /**
  29811. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29812. */
  29813. VertexBuffer.prototype.getIsInstanced = function () {
  29814. return this._instanced;
  29815. };
  29816. /**
  29817. * Returns the instancing divisor, zero for non-instanced (integer).
  29818. */
  29819. VertexBuffer.prototype.getInstanceDivisor = function () {
  29820. return this._instanceDivisor;
  29821. };
  29822. // Methods
  29823. /**
  29824. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29825. * Returns the created WebGLBuffer.
  29826. */
  29827. VertexBuffer.prototype.create = function (data) {
  29828. return this._buffer.create(data);
  29829. };
  29830. /**
  29831. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29832. * This function will create a new buffer if the current one is not updatable
  29833. * Returns the updated WebGLBuffer.
  29834. */
  29835. VertexBuffer.prototype.update = function (data) {
  29836. return this._buffer.update(data);
  29837. };
  29838. /**
  29839. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29840. * Returns the directly updated WebGLBuffer.
  29841. * @param data the new data
  29842. * @param offset the new offset
  29843. * @param useBytes set to true if the offset is in bytes
  29844. */
  29845. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29846. if (useBytes === void 0) { useBytes = false; }
  29847. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29848. };
  29849. /**
  29850. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29851. */
  29852. VertexBuffer.prototype.dispose = function () {
  29853. if (this._ownsBuffer) {
  29854. this._buffer.dispose();
  29855. }
  29856. };
  29857. /**
  29858. * Enumerates each value of this vertex buffer as numbers.
  29859. * @param count the number of values to enumerate
  29860. * @param callback the callback function called for each value
  29861. */
  29862. VertexBuffer.prototype.forEach = function (count, callback) {
  29863. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29864. };
  29865. Object.defineProperty(VertexBuffer, "PositionKind", {
  29866. get: function () {
  29867. return VertexBuffer._PositionKind;
  29868. },
  29869. enumerable: true,
  29870. configurable: true
  29871. });
  29872. Object.defineProperty(VertexBuffer, "NormalKind", {
  29873. get: function () {
  29874. return VertexBuffer._NormalKind;
  29875. },
  29876. enumerable: true,
  29877. configurable: true
  29878. });
  29879. Object.defineProperty(VertexBuffer, "TangentKind", {
  29880. get: function () {
  29881. return VertexBuffer._TangentKind;
  29882. },
  29883. enumerable: true,
  29884. configurable: true
  29885. });
  29886. Object.defineProperty(VertexBuffer, "UVKind", {
  29887. get: function () {
  29888. return VertexBuffer._UVKind;
  29889. },
  29890. enumerable: true,
  29891. configurable: true
  29892. });
  29893. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29894. get: function () {
  29895. return VertexBuffer._UV2Kind;
  29896. },
  29897. enumerable: true,
  29898. configurable: true
  29899. });
  29900. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29901. get: function () {
  29902. return VertexBuffer._UV3Kind;
  29903. },
  29904. enumerable: true,
  29905. configurable: true
  29906. });
  29907. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29908. get: function () {
  29909. return VertexBuffer._UV4Kind;
  29910. },
  29911. enumerable: true,
  29912. configurable: true
  29913. });
  29914. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29915. get: function () {
  29916. return VertexBuffer._UV5Kind;
  29917. },
  29918. enumerable: true,
  29919. configurable: true
  29920. });
  29921. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29922. get: function () {
  29923. return VertexBuffer._UV6Kind;
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. Object.defineProperty(VertexBuffer, "ColorKind", {
  29929. get: function () {
  29930. return VertexBuffer._ColorKind;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29936. get: function () {
  29937. return VertexBuffer._MatricesIndicesKind;
  29938. },
  29939. enumerable: true,
  29940. configurable: true
  29941. });
  29942. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29943. get: function () {
  29944. return VertexBuffer._MatricesWeightsKind;
  29945. },
  29946. enumerable: true,
  29947. configurable: true
  29948. });
  29949. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29950. get: function () {
  29951. return VertexBuffer._MatricesIndicesExtraKind;
  29952. },
  29953. enumerable: true,
  29954. configurable: true
  29955. });
  29956. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29957. get: function () {
  29958. return VertexBuffer._MatricesWeightsExtraKind;
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. /**
  29964. * Deduces the stride given a kind.
  29965. * @param kind The kind string to deduce
  29966. * @returns The deduced stride
  29967. */
  29968. VertexBuffer.DeduceStride = function (kind) {
  29969. switch (kind) {
  29970. case VertexBuffer.UVKind:
  29971. case VertexBuffer.UV2Kind:
  29972. case VertexBuffer.UV3Kind:
  29973. case VertexBuffer.UV4Kind:
  29974. case VertexBuffer.UV5Kind:
  29975. case VertexBuffer.UV6Kind:
  29976. return 2;
  29977. case VertexBuffer.NormalKind:
  29978. case VertexBuffer.PositionKind:
  29979. return 3;
  29980. case VertexBuffer.ColorKind:
  29981. case VertexBuffer.MatricesIndicesKind:
  29982. case VertexBuffer.MatricesIndicesExtraKind:
  29983. case VertexBuffer.MatricesWeightsKind:
  29984. case VertexBuffer.MatricesWeightsExtraKind:
  29985. case VertexBuffer.TangentKind:
  29986. return 4;
  29987. default:
  29988. throw new Error("Invalid kind '" + kind + "'");
  29989. }
  29990. };
  29991. /**
  29992. * Gets the byte length of the given type.
  29993. * @param type the type
  29994. * @returns the number of bytes
  29995. */
  29996. VertexBuffer.GetTypeByteLength = function (type) {
  29997. switch (type) {
  29998. case VertexBuffer.BYTE:
  29999. case VertexBuffer.UNSIGNED_BYTE:
  30000. return 1;
  30001. case VertexBuffer.SHORT:
  30002. case VertexBuffer.UNSIGNED_SHORT:
  30003. return 2;
  30004. case VertexBuffer.INT:
  30005. case VertexBuffer.FLOAT:
  30006. return 4;
  30007. default:
  30008. throw new Error("Invalid type '" + type + "'");
  30009. }
  30010. };
  30011. /**
  30012. * Enumerates each value of the given parameters as numbers.
  30013. * @param data the data to enumerate
  30014. * @param byteOffset the byte offset of the data
  30015. * @param byteStride the byte stride of the data
  30016. * @param componentCount the number of components per element
  30017. * @param componentType the type of the component
  30018. * @param count the total number of components
  30019. * @param normalized whether the data is normalized
  30020. * @param callback the callback function called for each value
  30021. */
  30022. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30023. if (data instanceof Array) {
  30024. var offset = byteOffset / 4;
  30025. var stride = byteStride / 4;
  30026. for (var index = 0; index < count; index += componentCount) {
  30027. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30028. callback(data[offset + componentIndex], index + componentIndex);
  30029. }
  30030. offset += stride;
  30031. }
  30032. }
  30033. else {
  30034. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30035. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30036. for (var index = 0; index < count; index += componentCount) {
  30037. var componentByteOffset = byteOffset;
  30038. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30039. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30040. callback(value, index + componentIndex);
  30041. componentByteOffset += componentByteLength;
  30042. }
  30043. byteOffset += byteStride;
  30044. }
  30045. }
  30046. };
  30047. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30048. switch (type) {
  30049. case VertexBuffer.BYTE: {
  30050. var value = dataView.getInt8(byteOffset);
  30051. if (normalized) {
  30052. value = Math.max(value / 127, -1);
  30053. }
  30054. return value;
  30055. }
  30056. case VertexBuffer.UNSIGNED_BYTE: {
  30057. var value = dataView.getUint8(byteOffset);
  30058. if (normalized) {
  30059. value = value / 255;
  30060. }
  30061. return value;
  30062. }
  30063. case VertexBuffer.SHORT: {
  30064. var value = dataView.getInt16(byteOffset, true);
  30065. if (normalized) {
  30066. value = Math.max(value / 16383, -1);
  30067. }
  30068. return value;
  30069. }
  30070. case VertexBuffer.UNSIGNED_SHORT: {
  30071. var value = dataView.getUint16(byteOffset, true);
  30072. if (normalized) {
  30073. value = value / 65535;
  30074. }
  30075. return value;
  30076. }
  30077. case VertexBuffer.FLOAT: {
  30078. return dataView.getFloat32(byteOffset, true);
  30079. }
  30080. default: {
  30081. throw new Error("Invalid component type " + type);
  30082. }
  30083. }
  30084. };
  30085. /**
  30086. * The byte type.
  30087. */
  30088. VertexBuffer.BYTE = 5120;
  30089. /**
  30090. * The unsigned byte type.
  30091. */
  30092. VertexBuffer.UNSIGNED_BYTE = 5121;
  30093. /**
  30094. * The short type.
  30095. */
  30096. VertexBuffer.SHORT = 5122;
  30097. /**
  30098. * The unsigned short type.
  30099. */
  30100. VertexBuffer.UNSIGNED_SHORT = 5123;
  30101. /**
  30102. * The integer type.
  30103. */
  30104. VertexBuffer.INT = 5124;
  30105. /**
  30106. * The unsigned integer type.
  30107. */
  30108. VertexBuffer.UNSIGNED_INT = 5125;
  30109. /**
  30110. * The float type.
  30111. */
  30112. VertexBuffer.FLOAT = 5126;
  30113. // Enums
  30114. VertexBuffer._PositionKind = "position";
  30115. VertexBuffer._NormalKind = "normal";
  30116. VertexBuffer._TangentKind = "tangent";
  30117. VertexBuffer._UVKind = "uv";
  30118. VertexBuffer._UV2Kind = "uv2";
  30119. VertexBuffer._UV3Kind = "uv3";
  30120. VertexBuffer._UV4Kind = "uv4";
  30121. VertexBuffer._UV5Kind = "uv5";
  30122. VertexBuffer._UV6Kind = "uv6";
  30123. VertexBuffer._ColorKind = "color";
  30124. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30125. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30126. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30127. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30128. return VertexBuffer;
  30129. }());
  30130. BABYLON.VertexBuffer = VertexBuffer;
  30131. })(BABYLON || (BABYLON = {}));
  30132. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30133. var BABYLON;
  30134. (function (BABYLON) {
  30135. /**
  30136. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30137. */
  30138. var DummyInternalTextureTracker = /** @class */ (function () {
  30139. function DummyInternalTextureTracker() {
  30140. /**
  30141. * Gets or set the previous tracker in the list
  30142. */
  30143. this.previous = null;
  30144. /**
  30145. * Gets or set the next tracker in the list
  30146. */
  30147. this.next = null;
  30148. }
  30149. return DummyInternalTextureTracker;
  30150. }());
  30151. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30152. })(BABYLON || (BABYLON = {}));
  30153. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30154. var BABYLON;
  30155. (function (BABYLON) {
  30156. /**
  30157. * Class used to store data associated with WebGL texture data for the engine
  30158. * This class should not be used directly
  30159. */
  30160. var InternalTexture = /** @class */ (function () {
  30161. /**
  30162. * Creates a new InternalTexture
  30163. * @param engine defines the engine to use
  30164. * @param dataSource defines the type of data that will be used
  30165. */
  30166. function InternalTexture(engine, dataSource) {
  30167. /**
  30168. * Observable called when the texture is loaded
  30169. */
  30170. this.onLoadedObservable = new BABYLON.Observable();
  30171. /**
  30172. * Gets or set the previous tracker in the list
  30173. */
  30174. this.previous = null;
  30175. /**
  30176. * Gets or set the next tracker in the list
  30177. */
  30178. this.next = null;
  30179. // Private
  30180. /** @hidden */
  30181. this._initialSlot = -1;
  30182. /** @hidden */
  30183. this._designatedSlot = -1;
  30184. /** @hidden */
  30185. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30186. /** @hidden */
  30187. this._comparisonFunction = 0;
  30188. /** @hidden */
  30189. this._sphericalPolynomial = null;
  30190. /** @hidden */
  30191. this._lodGenerationScale = 0;
  30192. /** @hidden */
  30193. this._lodGenerationOffset = 0;
  30194. /** @hidden */
  30195. this._isRGBD = false;
  30196. /** @hidden */
  30197. this._references = 1;
  30198. this._engine = engine;
  30199. this._dataSource = dataSource;
  30200. this._webGLTexture = engine._createTexture();
  30201. }
  30202. /**
  30203. * Gets the Engine the texture belongs to.
  30204. * @returns The babylon engine
  30205. */
  30206. InternalTexture.prototype.getEngine = function () {
  30207. return this._engine;
  30208. };
  30209. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30210. /**
  30211. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30212. */
  30213. get: function () {
  30214. return this._dataSource;
  30215. },
  30216. enumerable: true,
  30217. configurable: true
  30218. });
  30219. /**
  30220. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30221. */
  30222. InternalTexture.prototype.incrementReferences = function () {
  30223. this._references++;
  30224. };
  30225. /**
  30226. * Change the size of the texture (not the size of the content)
  30227. * @param width defines the new width
  30228. * @param height defines the new height
  30229. * @param depth defines the new depth (1 by default)
  30230. */
  30231. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30232. if (depth === void 0) { depth = 1; }
  30233. this.width = width;
  30234. this.height = height;
  30235. this.depth = depth;
  30236. this.baseWidth = width;
  30237. this.baseHeight = height;
  30238. this.baseDepth = depth;
  30239. this._size = width * height * depth;
  30240. };
  30241. /** @hidden */
  30242. InternalTexture.prototype._rebuild = function () {
  30243. var _this = this;
  30244. var proxy;
  30245. this.isReady = false;
  30246. this._cachedCoordinatesMode = null;
  30247. this._cachedWrapU = null;
  30248. this._cachedWrapV = null;
  30249. this._cachedAnisotropicFilteringLevel = null;
  30250. switch (this._dataSource) {
  30251. case InternalTexture.DATASOURCE_TEMP:
  30252. return;
  30253. case InternalTexture.DATASOURCE_URL:
  30254. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30255. _this.isReady = true;
  30256. }, null, this._buffer, undefined, this.format);
  30257. proxy._swapAndDie(this);
  30258. return;
  30259. case InternalTexture.DATASOURCE_RAW:
  30260. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30261. proxy._swapAndDie(this);
  30262. this.isReady = true;
  30263. return;
  30264. case InternalTexture.DATASOURCE_RAW3D:
  30265. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30266. proxy._swapAndDie(this);
  30267. this.isReady = true;
  30268. return;
  30269. case InternalTexture.DATASOURCE_DYNAMIC:
  30270. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30271. proxy._swapAndDie(this);
  30272. // The engine will make sure to update content so no need to flag it as isReady = true
  30273. return;
  30274. case InternalTexture.DATASOURCE_RENDERTARGET:
  30275. var options = new BABYLON.RenderTargetCreationOptions();
  30276. options.generateDepthBuffer = this._generateDepthBuffer;
  30277. options.generateMipMaps = this.generateMipMaps;
  30278. options.generateStencilBuffer = this._generateStencilBuffer;
  30279. options.samplingMode = this.samplingMode;
  30280. options.type = this.type;
  30281. if (this.isCube) {
  30282. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30283. }
  30284. else {
  30285. var size = {
  30286. width: this.width,
  30287. height: this.height
  30288. };
  30289. proxy = this._engine.createRenderTargetTexture(size, options);
  30290. }
  30291. proxy._swapAndDie(this);
  30292. this.isReady = true;
  30293. return;
  30294. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30295. var depthTextureOptions = {
  30296. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30297. comparisonFunction: this._comparisonFunction,
  30298. generateStencil: this._generateStencilBuffer,
  30299. isCube: this.isCube
  30300. };
  30301. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30302. proxy._swapAndDie(this);
  30303. this.isReady = true;
  30304. return;
  30305. case InternalTexture.DATASOURCE_CUBE:
  30306. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30307. _this.isReady = true;
  30308. }, null, this.format, this._extension);
  30309. proxy._swapAndDie(this);
  30310. return;
  30311. case InternalTexture.DATASOURCE_CUBERAW:
  30312. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30313. proxy._swapAndDie(this);
  30314. this.isReady = true;
  30315. return;
  30316. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30317. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30318. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30319. _this.isReady = true;
  30320. });
  30321. proxy._swapAndDie(this);
  30322. return;
  30323. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30324. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30325. if (proxy) {
  30326. proxy._swapAndDie(_this);
  30327. }
  30328. _this.isReady = true;
  30329. }, null, this.format, this._extension);
  30330. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30331. return;
  30332. }
  30333. };
  30334. InternalTexture.prototype._swapAndDie = function (target) {
  30335. target._webGLTexture = this._webGLTexture;
  30336. if (this._framebuffer) {
  30337. target._framebuffer = this._framebuffer;
  30338. }
  30339. if (this._depthStencilBuffer) {
  30340. target._depthStencilBuffer = this._depthStencilBuffer;
  30341. }
  30342. if (this._lodTextureHigh) {
  30343. if (target._lodTextureHigh) {
  30344. target._lodTextureHigh.dispose();
  30345. }
  30346. target._lodTextureHigh = this._lodTextureHigh;
  30347. }
  30348. if (this._lodTextureMid) {
  30349. if (target._lodTextureMid) {
  30350. target._lodTextureMid.dispose();
  30351. }
  30352. target._lodTextureMid = this._lodTextureMid;
  30353. }
  30354. if (this._lodTextureLow) {
  30355. if (target._lodTextureLow) {
  30356. target._lodTextureLow.dispose();
  30357. }
  30358. target._lodTextureLow = this._lodTextureLow;
  30359. }
  30360. var cache = this._engine.getLoadedTexturesCache();
  30361. var index = cache.indexOf(this);
  30362. if (index !== -1) {
  30363. cache.splice(index, 1);
  30364. }
  30365. };
  30366. /**
  30367. * Dispose the current allocated resources
  30368. */
  30369. InternalTexture.prototype.dispose = function () {
  30370. if (!this._webGLTexture) {
  30371. return;
  30372. }
  30373. this._references--;
  30374. if (this._references === 0) {
  30375. this._engine._releaseTexture(this);
  30376. this._webGLTexture = null;
  30377. this.previous = null;
  30378. this.next = null;
  30379. }
  30380. };
  30381. /**
  30382. * The source of the texture data is unknown
  30383. */
  30384. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30385. /**
  30386. * Texture data comes from an URL
  30387. */
  30388. InternalTexture.DATASOURCE_URL = 1;
  30389. /**
  30390. * Texture data is only used for temporary storage
  30391. */
  30392. InternalTexture.DATASOURCE_TEMP = 2;
  30393. /**
  30394. * Texture data comes from raw data (ArrayBuffer)
  30395. */
  30396. InternalTexture.DATASOURCE_RAW = 3;
  30397. /**
  30398. * Texture content is dynamic (video or dynamic texture)
  30399. */
  30400. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30401. /**
  30402. * Texture content is generated by rendering to it
  30403. */
  30404. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30405. /**
  30406. * Texture content is part of a multi render target process
  30407. */
  30408. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30409. /**
  30410. * Texture data comes from a cube data file
  30411. */
  30412. InternalTexture.DATASOURCE_CUBE = 7;
  30413. /**
  30414. * Texture data comes from a raw cube data
  30415. */
  30416. InternalTexture.DATASOURCE_CUBERAW = 8;
  30417. /**
  30418. * Texture data come from a prefiltered cube data file
  30419. */
  30420. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30421. /**
  30422. * Texture content is raw 3D data
  30423. */
  30424. InternalTexture.DATASOURCE_RAW3D = 10;
  30425. /**
  30426. * Texture content is a depth texture
  30427. */
  30428. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30429. /**
  30430. * Texture data comes from a raw cube data encoded with RGBD
  30431. */
  30432. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30433. return InternalTexture;
  30434. }());
  30435. BABYLON.InternalTexture = InternalTexture;
  30436. })(BABYLON || (BABYLON = {}));
  30437. //# sourceMappingURL=babylon.internalTexture.js.map
  30438. var BABYLON;
  30439. (function (BABYLON) {
  30440. var BaseTexture = /** @class */ (function () {
  30441. function BaseTexture(scene) {
  30442. this._hasAlpha = false;
  30443. this.getAlphaFromRGB = false;
  30444. this.level = 1;
  30445. this.coordinatesIndex = 0;
  30446. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30447. /**
  30448. * | Value | Type | Description |
  30449. * | ----- | ------------------ | ----------- |
  30450. * | 0 | CLAMP_ADDRESSMODE | |
  30451. * | 1 | WRAP_ADDRESSMODE | |
  30452. * | 2 | MIRROR_ADDRESSMODE | |
  30453. */
  30454. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30455. /**
  30456. * | Value | Type | Description |
  30457. * | ----- | ------------------ | ----------- |
  30458. * | 0 | CLAMP_ADDRESSMODE | |
  30459. * | 1 | WRAP_ADDRESSMODE | |
  30460. * | 2 | MIRROR_ADDRESSMODE | |
  30461. */
  30462. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30463. /**
  30464. * | Value | Type | Description |
  30465. * | ----- | ------------------ | ----------- |
  30466. * | 0 | CLAMP_ADDRESSMODE | |
  30467. * | 1 | WRAP_ADDRESSMODE | |
  30468. * | 2 | MIRROR_ADDRESSMODE | |
  30469. */
  30470. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30471. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30472. this.isCube = false;
  30473. this.is3D = false;
  30474. this.gammaSpace = true;
  30475. this.invertZ = false;
  30476. this.lodLevelInAlpha = false;
  30477. this.isRenderTarget = false;
  30478. this.animations = new Array();
  30479. /**
  30480. * An event triggered when the texture is disposed.
  30481. */
  30482. this.onDisposeObservable = new BABYLON.Observable();
  30483. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30484. this._cachedSize = BABYLON.Size.Zero();
  30485. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30486. if (this._scene) {
  30487. this._scene.textures.push(this);
  30488. }
  30489. this._uid = null;
  30490. }
  30491. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30492. get: function () {
  30493. return this._hasAlpha;
  30494. },
  30495. set: function (value) {
  30496. if (this._hasAlpha === value) {
  30497. return;
  30498. }
  30499. this._hasAlpha = value;
  30500. if (this._scene) {
  30501. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30502. }
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30508. get: function () {
  30509. return this._coordinatesMode;
  30510. },
  30511. /**
  30512. * How a texture is mapped.
  30513. *
  30514. * | Value | Type | Description |
  30515. * | ----- | ----------------------------------- | ----------- |
  30516. * | 0 | EXPLICIT_MODE | |
  30517. * | 1 | SPHERICAL_MODE | |
  30518. * | 2 | PLANAR_MODE | |
  30519. * | 3 | CUBIC_MODE | |
  30520. * | 4 | PROJECTION_MODE | |
  30521. * | 5 | SKYBOX_MODE | |
  30522. * | 6 | INVCUBIC_MODE | |
  30523. * | 7 | EQUIRECTANGULAR_MODE | |
  30524. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30525. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30526. */
  30527. set: function (value) {
  30528. if (this._coordinatesMode === value) {
  30529. return;
  30530. }
  30531. this._coordinatesMode = value;
  30532. if (this._scene) {
  30533. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30534. }
  30535. },
  30536. enumerable: true,
  30537. configurable: true
  30538. });
  30539. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30540. /**
  30541. * Gets whether or not the texture contains RGBD data.
  30542. */
  30543. get: function () {
  30544. return this._texture != null && this._texture._isRGBD;
  30545. },
  30546. enumerable: true,
  30547. configurable: true
  30548. });
  30549. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30550. get: function () {
  30551. if (this._texture)
  30552. return this._texture._lodGenerationOffset;
  30553. return 0.0;
  30554. },
  30555. set: function (value) {
  30556. if (this._texture)
  30557. this._texture._lodGenerationOffset = value;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30563. get: function () {
  30564. if (this._texture)
  30565. return this._texture._lodGenerationScale;
  30566. return 0.0;
  30567. },
  30568. set: function (value) {
  30569. if (this._texture)
  30570. this._texture._lodGenerationScale = value;
  30571. },
  30572. enumerable: true,
  30573. configurable: true
  30574. });
  30575. Object.defineProperty(BaseTexture.prototype, "uid", {
  30576. get: function () {
  30577. if (!this._uid) {
  30578. this._uid = BABYLON.Tools.RandomId();
  30579. }
  30580. return this._uid;
  30581. },
  30582. enumerable: true,
  30583. configurable: true
  30584. });
  30585. BaseTexture.prototype.toString = function () {
  30586. return this.name;
  30587. };
  30588. BaseTexture.prototype.getClassName = function () {
  30589. return "BaseTexture";
  30590. };
  30591. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30592. set: function (callback) {
  30593. if (this._onDisposeObserver) {
  30594. this.onDisposeObservable.remove(this._onDisposeObserver);
  30595. }
  30596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30597. },
  30598. enumerable: true,
  30599. configurable: true
  30600. });
  30601. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30602. get: function () {
  30603. return true;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. BaseTexture.prototype.getScene = function () {
  30609. return this._scene;
  30610. };
  30611. BaseTexture.prototype.getTextureMatrix = function () {
  30612. return BABYLON.Matrix.IdentityReadOnly;
  30613. };
  30614. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30615. return BABYLON.Matrix.IdentityReadOnly;
  30616. };
  30617. BaseTexture.prototype.getInternalTexture = function () {
  30618. return this._texture;
  30619. };
  30620. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30621. return !this.isBlocking || this.isReady();
  30622. };
  30623. BaseTexture.prototype.isReady = function () {
  30624. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30625. this.delayLoad();
  30626. return false;
  30627. }
  30628. if (this._texture) {
  30629. return this._texture.isReady;
  30630. }
  30631. return false;
  30632. };
  30633. BaseTexture.prototype.getSize = function () {
  30634. if (this._texture) {
  30635. if (this._texture.width) {
  30636. this._cachedSize.width = this._texture.width;
  30637. this._cachedSize.height = this._texture.height;
  30638. return this._cachedSize;
  30639. }
  30640. if (this._texture._size) {
  30641. this._cachedSize.width = this._texture._size;
  30642. this._cachedSize.height = this._texture._size;
  30643. return this._cachedSize;
  30644. }
  30645. }
  30646. return this._cachedSize;
  30647. };
  30648. BaseTexture.prototype.getBaseSize = function () {
  30649. if (!this.isReady() || !this._texture)
  30650. return BABYLON.Size.Zero();
  30651. if (this._texture._size) {
  30652. return new BABYLON.Size(this._texture._size, this._texture._size);
  30653. }
  30654. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30655. };
  30656. BaseTexture.prototype.scale = function (ratio) {
  30657. };
  30658. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30659. get: function () {
  30660. return false;
  30661. },
  30662. enumerable: true,
  30663. configurable: true
  30664. });
  30665. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30666. if (!this._scene) {
  30667. return null;
  30668. }
  30669. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30670. for (var index = 0; index < texturesCache.length; index++) {
  30671. var texturesCacheEntry = texturesCache[index];
  30672. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30673. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30674. texturesCacheEntry.incrementReferences();
  30675. return texturesCacheEntry;
  30676. }
  30677. }
  30678. }
  30679. return null;
  30680. };
  30681. BaseTexture.prototype._rebuild = function () {
  30682. };
  30683. BaseTexture.prototype.delayLoad = function () {
  30684. };
  30685. BaseTexture.prototype.clone = function () {
  30686. return null;
  30687. };
  30688. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30689. get: function () {
  30690. if (!this._texture) {
  30691. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30692. }
  30693. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30694. },
  30695. enumerable: true,
  30696. configurable: true
  30697. });
  30698. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30699. get: function () {
  30700. if (!this._texture) {
  30701. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30702. }
  30703. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. /**
  30709. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30710. * This will returns an RGBA array buffer containing either in values (0-255) or
  30711. * float values (0-1) depending of the underlying buffer type.
  30712. * @param faceIndex The face of the texture to read (in case of cube texture)
  30713. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30714. * @returns The Array buffer containing the pixels data.
  30715. */
  30716. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30717. if (faceIndex === void 0) { faceIndex = 0; }
  30718. if (level === void 0) { level = 0; }
  30719. if (!this._texture) {
  30720. return null;
  30721. }
  30722. var size = this.getSize();
  30723. var width = size.width;
  30724. var height = size.height;
  30725. var scene = this.getScene();
  30726. if (!scene) {
  30727. return null;
  30728. }
  30729. var engine = scene.getEngine();
  30730. if (level != 0) {
  30731. width = width / Math.pow(2, level);
  30732. height = height / Math.pow(2, level);
  30733. width = Math.round(width);
  30734. height = Math.round(height);
  30735. }
  30736. if (this._texture.isCube) {
  30737. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30738. }
  30739. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30740. };
  30741. BaseTexture.prototype.releaseInternalTexture = function () {
  30742. if (this._texture) {
  30743. this._texture.dispose();
  30744. this._texture = null;
  30745. }
  30746. };
  30747. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30748. get: function () {
  30749. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30750. return null;
  30751. }
  30752. if (!this._texture._sphericalPolynomial) {
  30753. this._texture._sphericalPolynomial =
  30754. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30755. }
  30756. return this._texture._sphericalPolynomial;
  30757. },
  30758. set: function (value) {
  30759. if (this._texture) {
  30760. this._texture._sphericalPolynomial = value;
  30761. }
  30762. },
  30763. enumerable: true,
  30764. configurable: true
  30765. });
  30766. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30767. get: function () {
  30768. if (this._texture) {
  30769. return this._texture._lodTextureHigh;
  30770. }
  30771. return null;
  30772. },
  30773. enumerable: true,
  30774. configurable: true
  30775. });
  30776. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30777. get: function () {
  30778. if (this._texture) {
  30779. return this._texture._lodTextureMid;
  30780. }
  30781. return null;
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30787. get: function () {
  30788. if (this._texture) {
  30789. return this._texture._lodTextureLow;
  30790. }
  30791. return null;
  30792. },
  30793. enumerable: true,
  30794. configurable: true
  30795. });
  30796. BaseTexture.prototype.dispose = function () {
  30797. if (!this._scene) {
  30798. return;
  30799. }
  30800. // Animations
  30801. this._scene.stopAnimation(this);
  30802. // Remove from scene
  30803. this._scene._removePendingData(this);
  30804. var index = this._scene.textures.indexOf(this);
  30805. if (index >= 0) {
  30806. this._scene.textures.splice(index, 1);
  30807. }
  30808. if (this._texture === undefined) {
  30809. return;
  30810. }
  30811. // Release
  30812. this.releaseInternalTexture();
  30813. // Callback
  30814. this.onDisposeObservable.notifyObservers(this);
  30815. this.onDisposeObservable.clear();
  30816. };
  30817. BaseTexture.prototype.serialize = function () {
  30818. if (!this.name) {
  30819. return null;
  30820. }
  30821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30822. // Animations
  30823. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30824. return serializationObject;
  30825. };
  30826. BaseTexture.WhenAllReady = function (textures, callback) {
  30827. var numRemaining = textures.length;
  30828. if (numRemaining === 0) {
  30829. callback();
  30830. return;
  30831. }
  30832. var _loop_1 = function () {
  30833. texture = textures[i];
  30834. if (texture.isReady()) {
  30835. if (--numRemaining === 0) {
  30836. callback();
  30837. }
  30838. }
  30839. else {
  30840. onLoadObservable = texture.onLoadObservable;
  30841. var onLoadCallback_1 = function () {
  30842. onLoadObservable.removeCallback(onLoadCallback_1);
  30843. if (--numRemaining === 0) {
  30844. callback();
  30845. }
  30846. };
  30847. onLoadObservable.add(onLoadCallback_1);
  30848. }
  30849. };
  30850. var texture, onLoadObservable;
  30851. for (var i = 0; i < textures.length; i++) {
  30852. _loop_1();
  30853. }
  30854. };
  30855. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], BaseTexture.prototype, "name", void 0);
  30859. __decorate([
  30860. BABYLON.serialize("hasAlpha")
  30861. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], BaseTexture.prototype, "level", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30871. __decorate([
  30872. BABYLON.serialize("coordinatesMode")
  30873. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "wrapU", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], BaseTexture.prototype, "wrapV", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "wrapR", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], BaseTexture.prototype, "isCube", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], BaseTexture.prototype, "is3D", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], BaseTexture.prototype, "gammaSpace", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], BaseTexture.prototype, "invertZ", void 0);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30904. __decorate([
  30905. BABYLON.serialize()
  30906. ], BaseTexture.prototype, "lodGenerationScale", null);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30910. return BaseTexture;
  30911. }());
  30912. BABYLON.BaseTexture = BaseTexture;
  30913. })(BABYLON || (BABYLON = {}));
  30914. //# sourceMappingURL=babylon.baseTexture.js.map
  30915. var BABYLON;
  30916. (function (BABYLON) {
  30917. var Texture = /** @class */ (function (_super) {
  30918. __extends(Texture, _super);
  30919. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30920. if (noMipmap === void 0) { noMipmap = false; }
  30921. if (invertY === void 0) { invertY = true; }
  30922. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30923. if (onLoad === void 0) { onLoad = null; }
  30924. if (onError === void 0) { onError = null; }
  30925. if (buffer === void 0) { buffer = null; }
  30926. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30927. var _this = _super.call(this, scene) || this;
  30928. _this.uOffset = 0;
  30929. _this.vOffset = 0;
  30930. _this.uScale = 1.0;
  30931. _this.vScale = 1.0;
  30932. _this.uAng = 0;
  30933. _this.vAng = 0;
  30934. _this.wAng = 0;
  30935. /**
  30936. * Defines the center of rotation (U)
  30937. */
  30938. _this.uRotationCenter = 0.5;
  30939. /**
  30940. * Defines the center of rotation (V)
  30941. */
  30942. _this.vRotationCenter = 0.5;
  30943. /**
  30944. * Defines the center of rotation (W)
  30945. */
  30946. _this.wRotationCenter = 0.5;
  30947. _this._isBlocking = true;
  30948. _this.name = url || "";
  30949. _this.url = url;
  30950. _this._noMipmap = noMipmap;
  30951. _this._invertY = invertY;
  30952. _this._samplingMode = samplingMode;
  30953. _this._buffer = buffer;
  30954. _this._deleteBuffer = deleteBuffer;
  30955. if (format) {
  30956. _this._format = format;
  30957. }
  30958. scene = _this.getScene();
  30959. if (!scene) {
  30960. return _this;
  30961. }
  30962. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30963. var load = function () {
  30964. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30965. _this.onLoadObservable.notifyObservers(_this);
  30966. }
  30967. if (onLoad) {
  30968. onLoad();
  30969. }
  30970. if (!_this.isBlocking && scene) {
  30971. scene.resetCachedMaterial();
  30972. }
  30973. };
  30974. if (!_this.url) {
  30975. _this._delayedOnLoad = load;
  30976. _this._delayedOnError = onError;
  30977. return _this;
  30978. }
  30979. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30980. if (!_this._texture) {
  30981. if (!scene.useDelayedTextureLoading) {
  30982. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30983. if (deleteBuffer) {
  30984. delete _this._buffer;
  30985. }
  30986. }
  30987. else {
  30988. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30989. _this._delayedOnLoad = load;
  30990. _this._delayedOnError = onError;
  30991. }
  30992. }
  30993. else {
  30994. if (_this._texture.isReady) {
  30995. BABYLON.Tools.SetImmediate(function () { return load(); });
  30996. }
  30997. else {
  30998. _this._texture.onLoadedObservable.add(load);
  30999. }
  31000. }
  31001. return _this;
  31002. }
  31003. Object.defineProperty(Texture.prototype, "noMipmap", {
  31004. get: function () {
  31005. return this._noMipmap;
  31006. },
  31007. enumerable: true,
  31008. configurable: true
  31009. });
  31010. Object.defineProperty(Texture.prototype, "isBlocking", {
  31011. get: function () {
  31012. return this._isBlocking;
  31013. },
  31014. set: function (value) {
  31015. this._isBlocking = value;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Texture.prototype, "samplingMode", {
  31021. get: function () {
  31022. return this._samplingMode;
  31023. },
  31024. enumerable: true,
  31025. configurable: true
  31026. });
  31027. /**
  31028. * Update the url (and optional buffer) of this texture if url was null during construction.
  31029. * @param url the url of the texture
  31030. * @param buffer the buffer of the texture (defaults to null)
  31031. */
  31032. Texture.prototype.updateURL = function (url, buffer) {
  31033. if (buffer === void 0) { buffer = null; }
  31034. if (this.url) {
  31035. throw new Error("URL is already set");
  31036. }
  31037. this.url = url;
  31038. this._buffer = buffer;
  31039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31040. this.delayLoad();
  31041. };
  31042. Texture.prototype.delayLoad = function () {
  31043. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31044. return;
  31045. }
  31046. var scene = this.getScene();
  31047. if (!scene) {
  31048. return;
  31049. }
  31050. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31051. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31052. if (!this._texture) {
  31053. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31054. if (this._deleteBuffer) {
  31055. delete this._buffer;
  31056. }
  31057. }
  31058. else {
  31059. if (this._delayedOnLoad) {
  31060. if (this._texture.isReady) {
  31061. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31062. }
  31063. else {
  31064. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31065. }
  31066. }
  31067. }
  31068. this._delayedOnLoad = null;
  31069. this._delayedOnError = null;
  31070. };
  31071. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31072. if (!this._texture) {
  31073. return;
  31074. }
  31075. var scene = this.getScene();
  31076. if (!scene) {
  31077. return;
  31078. }
  31079. this._samplingMode = samplingMode;
  31080. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31081. };
  31082. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31083. x *= this.uScale;
  31084. y *= this.vScale;
  31085. x -= this.uRotationCenter * this.uScale;
  31086. y -= this.vRotationCenter * this.vScale;
  31087. z -= this.wRotationCenter;
  31088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31089. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31090. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31091. t.z += this.wRotationCenter;
  31092. };
  31093. Texture.prototype.getTextureMatrix = function () {
  31094. var _this = this;
  31095. if (this.uOffset === this._cachedUOffset &&
  31096. this.vOffset === this._cachedVOffset &&
  31097. this.uScale === this._cachedUScale &&
  31098. this.vScale === this._cachedVScale &&
  31099. this.uAng === this._cachedUAng &&
  31100. this.vAng === this._cachedVAng &&
  31101. this.wAng === this._cachedWAng) {
  31102. return this._cachedTextureMatrix;
  31103. }
  31104. this._cachedUOffset = this.uOffset;
  31105. this._cachedVOffset = this.vOffset;
  31106. this._cachedUScale = this.uScale;
  31107. this._cachedVScale = this.vScale;
  31108. this._cachedUAng = this.uAng;
  31109. this._cachedVAng = this.vAng;
  31110. this._cachedWAng = this.wAng;
  31111. if (!this._cachedTextureMatrix) {
  31112. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31113. this._rowGenerationMatrix = new BABYLON.Matrix();
  31114. this._t0 = BABYLON.Vector3.Zero();
  31115. this._t1 = BABYLON.Vector3.Zero();
  31116. this._t2 = BABYLON.Vector3.Zero();
  31117. }
  31118. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31119. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31120. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31121. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31122. this._t1.subtractInPlace(this._t0);
  31123. this._t2.subtractInPlace(this._t0);
  31124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31125. this._cachedTextureMatrix.m[0] = this._t1.x;
  31126. this._cachedTextureMatrix.m[1] = this._t1.y;
  31127. this._cachedTextureMatrix.m[2] = this._t1.z;
  31128. this._cachedTextureMatrix.m[4] = this._t2.x;
  31129. this._cachedTextureMatrix.m[5] = this._t2.y;
  31130. this._cachedTextureMatrix.m[6] = this._t2.z;
  31131. this._cachedTextureMatrix.m[8] = this._t0.x;
  31132. this._cachedTextureMatrix.m[9] = this._t0.y;
  31133. this._cachedTextureMatrix.m[10] = this._t0.z;
  31134. var scene = this.getScene();
  31135. if (!scene) {
  31136. return this._cachedTextureMatrix;
  31137. }
  31138. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31139. return mat.hasTexture(_this);
  31140. });
  31141. return this._cachedTextureMatrix;
  31142. };
  31143. Texture.prototype.getReflectionTextureMatrix = function () {
  31144. var _this = this;
  31145. var scene = this.getScene();
  31146. if (!scene) {
  31147. return this._cachedTextureMatrix;
  31148. }
  31149. if (this.uOffset === this._cachedUOffset &&
  31150. this.vOffset === this._cachedVOffset &&
  31151. this.uScale === this._cachedUScale &&
  31152. this.vScale === this._cachedVScale &&
  31153. this.coordinatesMode === this._cachedCoordinatesMode) {
  31154. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31155. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31156. return this._cachedTextureMatrix;
  31157. }
  31158. }
  31159. else {
  31160. return this._cachedTextureMatrix;
  31161. }
  31162. }
  31163. if (!this._cachedTextureMatrix) {
  31164. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31165. }
  31166. if (!this._projectionModeMatrix) {
  31167. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31168. }
  31169. this._cachedUOffset = this.uOffset;
  31170. this._cachedVOffset = this.vOffset;
  31171. this._cachedUScale = this.uScale;
  31172. this._cachedVScale = this.vScale;
  31173. this._cachedCoordinatesMode = this.coordinatesMode;
  31174. switch (this.coordinatesMode) {
  31175. case Texture.PLANAR_MODE:
  31176. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31177. this._cachedTextureMatrix[0] = this.uScale;
  31178. this._cachedTextureMatrix[5] = this.vScale;
  31179. this._cachedTextureMatrix[12] = this.uOffset;
  31180. this._cachedTextureMatrix[13] = this.vOffset;
  31181. break;
  31182. case Texture.PROJECTION_MODE:
  31183. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31184. this._projectionModeMatrix.m[0] = 0.5;
  31185. this._projectionModeMatrix.m[5] = -0.5;
  31186. this._projectionModeMatrix.m[10] = 0.0;
  31187. this._projectionModeMatrix.m[12] = 0.5;
  31188. this._projectionModeMatrix.m[13] = 0.5;
  31189. this._projectionModeMatrix.m[14] = 1.0;
  31190. this._projectionModeMatrix.m[15] = 1.0;
  31191. var projectionMatrix = scene.getProjectionMatrix();
  31192. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31193. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31194. break;
  31195. default:
  31196. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31197. break;
  31198. }
  31199. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31200. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31201. });
  31202. return this._cachedTextureMatrix;
  31203. };
  31204. Texture.prototype.clone = function () {
  31205. var _this = this;
  31206. return BABYLON.SerializationHelper.Clone(function () {
  31207. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31208. }, this);
  31209. };
  31210. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31211. get: function () {
  31212. if (!this._onLoadObservable) {
  31213. this._onLoadObservable = new BABYLON.Observable();
  31214. }
  31215. return this._onLoadObservable;
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. Texture.prototype.serialize = function () {
  31221. var serializationObject = _super.prototype.serialize.call(this);
  31222. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31223. serializationObject.base64String = this._buffer;
  31224. serializationObject.name = serializationObject.name.replace("data:", "");
  31225. }
  31226. serializationObject.invertY = this._invertY;
  31227. serializationObject.samplingMode = this.samplingMode;
  31228. return serializationObject;
  31229. };
  31230. Texture.prototype.getClassName = function () {
  31231. return "Texture";
  31232. };
  31233. Texture.prototype.dispose = function () {
  31234. _super.prototype.dispose.call(this);
  31235. if (this._onLoadObservable) {
  31236. this._onLoadObservable.clear();
  31237. this._onLoadObservable = null;
  31238. }
  31239. this._delayedOnLoad = null;
  31240. this._delayedOnError = null;
  31241. };
  31242. // Statics
  31243. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31244. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31245. if (onLoad === void 0) { onLoad = null; }
  31246. if (onError === void 0) { onError = null; }
  31247. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31248. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31249. };
  31250. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31251. if (parsedTexture.customType) {
  31252. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31253. // Update Sampling Mode
  31254. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31255. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31256. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31257. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31258. }
  31259. }
  31260. return parsedCustomTexture;
  31261. }
  31262. if (parsedTexture.isCube) {
  31263. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31264. }
  31265. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31266. return null;
  31267. }
  31268. var texture = BABYLON.SerializationHelper.Parse(function () {
  31269. var generateMipMaps = true;
  31270. if (parsedTexture.noMipmap) {
  31271. generateMipMaps = false;
  31272. }
  31273. if (parsedTexture.mirrorPlane) {
  31274. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31275. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31276. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31277. return mirrorTexture;
  31278. }
  31279. else if (parsedTexture.isRenderTarget) {
  31280. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31281. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31282. return renderTargetTexture;
  31283. }
  31284. else {
  31285. var texture;
  31286. if (parsedTexture.base64String) {
  31287. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31288. }
  31289. else {
  31290. var url = rootUrl + parsedTexture.name;
  31291. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31292. url = parsedTexture.url;
  31293. }
  31294. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31295. }
  31296. return texture;
  31297. }
  31298. }, parsedTexture, scene);
  31299. // Update Sampling Mode
  31300. if (parsedTexture.samplingMode) {
  31301. var sampling = parsedTexture.samplingMode;
  31302. if (texture._samplingMode !== sampling) {
  31303. texture.updateSamplingMode(sampling);
  31304. }
  31305. }
  31306. // Animations
  31307. if (parsedTexture.animations) {
  31308. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31309. var parsedAnimation = parsedTexture.animations[animationIndex];
  31310. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31311. }
  31312. }
  31313. return texture;
  31314. };
  31315. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31316. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31317. if (noMipmap === void 0) { noMipmap = false; }
  31318. if (invertY === void 0) { invertY = true; }
  31319. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31320. if (onLoad === void 0) { onLoad = null; }
  31321. if (onError === void 0) { onError = null; }
  31322. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31323. if (name.substr(0, 5) !== "data:") {
  31324. name = "data:" + name;
  31325. }
  31326. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31327. };
  31328. // Constants
  31329. Texture.NEAREST_SAMPLINGMODE = 1;
  31330. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31331. Texture.BILINEAR_SAMPLINGMODE = 2;
  31332. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31333. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31334. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31335. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31336. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31337. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31338. Texture.NEAREST_LINEAR = 7;
  31339. Texture.NEAREST_NEAREST = 8;
  31340. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31341. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31342. Texture.LINEAR_LINEAR = 11;
  31343. Texture.LINEAR_NEAREST = 12;
  31344. Texture.EXPLICIT_MODE = 0;
  31345. Texture.SPHERICAL_MODE = 1;
  31346. Texture.PLANAR_MODE = 2;
  31347. Texture.CUBIC_MODE = 3;
  31348. Texture.PROJECTION_MODE = 4;
  31349. Texture.SKYBOX_MODE = 5;
  31350. Texture.INVCUBIC_MODE = 6;
  31351. Texture.EQUIRECTANGULAR_MODE = 7;
  31352. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31353. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31354. Texture.CLAMP_ADDRESSMODE = 0;
  31355. Texture.WRAP_ADDRESSMODE = 1;
  31356. Texture.MIRROR_ADDRESSMODE = 2;
  31357. /**
  31358. * 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
  31359. */
  31360. Texture.UseSerializedUrlIfAny = false;
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Texture.prototype, "url", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Texture.prototype, "uOffset", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Texture.prototype, "vOffset", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Texture.prototype, "uScale", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], Texture.prototype, "vScale", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Texture.prototype, "uAng", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Texture.prototype, "vAng", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], Texture.prototype, "wAng", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Texture.prototype, "uRotationCenter", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Texture.prototype, "vRotationCenter", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], Texture.prototype, "wRotationCenter", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], Texture.prototype, "isBlocking", null);
  31397. return Texture;
  31398. }(BABYLON.BaseTexture));
  31399. BABYLON.Texture = Texture;
  31400. })(BABYLON || (BABYLON = {}));
  31401. //# sourceMappingURL=babylon.texture.js.map
  31402. var BABYLON;
  31403. (function (BABYLON) {
  31404. /**
  31405. * @hidden
  31406. **/
  31407. var _InstancesBatch = /** @class */ (function () {
  31408. function _InstancesBatch() {
  31409. this.mustReturn = false;
  31410. this.visibleInstances = new Array();
  31411. this.renderSelf = new Array();
  31412. }
  31413. return _InstancesBatch;
  31414. }());
  31415. BABYLON._InstancesBatch = _InstancesBatch;
  31416. var Mesh = /** @class */ (function (_super) {
  31417. __extends(Mesh, _super);
  31418. /**
  31419. * @constructor
  31420. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31421. * @param {Scene} scene The scene to add this mesh to.
  31422. * @param {Node} parent The parent of this mesh, if it has one
  31423. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31424. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31425. * When false, achieved by calling a clone(), also passing False.
  31426. * This will make creation of children, recursive.
  31427. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31428. */
  31429. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31430. if (scene === void 0) { scene = null; }
  31431. if (parent === void 0) { parent = null; }
  31432. if (source === void 0) { source = null; }
  31433. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31434. var _this = _super.call(this, name, scene) || this;
  31435. // Events
  31436. /**
  31437. * An event triggered before rendering the mesh
  31438. */
  31439. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31440. /**
  31441. * An event triggered after rendering the mesh
  31442. */
  31443. _this.onAfterRenderObservable = new BABYLON.Observable();
  31444. /**
  31445. * An event triggered before drawing the mesh
  31446. */
  31447. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31448. // Members
  31449. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31450. _this.instances = new Array();
  31451. _this._LODLevels = new Array();
  31452. _this._visibleInstances = {};
  31453. _this._renderIdForInstances = new Array();
  31454. _this._batchCache = new _InstancesBatch();
  31455. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31456. // Use by builder only to know what orientation were the mesh build in.
  31457. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31458. _this.overrideMaterialSideOrientation = null;
  31459. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31460. // Will be used to save a source mesh reference, If any
  31461. _this._source = null;
  31462. scene = _this.getScene();
  31463. if (source) {
  31464. // Geometry
  31465. if (source._geometry) {
  31466. source._geometry.applyToMesh(_this);
  31467. }
  31468. // Deep copy
  31469. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31470. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31471. // Source mesh
  31472. _this._source = source;
  31473. // Metadata
  31474. if (source.metadata && source.metadata.clone) {
  31475. _this.metadata = source.metadata.clone();
  31476. }
  31477. else {
  31478. _this.metadata = source.metadata;
  31479. }
  31480. // Tags
  31481. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31482. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31483. }
  31484. // Parent
  31485. _this.parent = source.parent;
  31486. // Pivot
  31487. _this.setPivotMatrix(source.getPivotMatrix());
  31488. _this.id = name + "." + source.id;
  31489. // Material
  31490. _this.material = source.material;
  31491. var index;
  31492. if (!doNotCloneChildren) {
  31493. // Children
  31494. var directDescendants = source.getDescendants(true);
  31495. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31496. var child = directDescendants[index_1];
  31497. if (child.clone) {
  31498. child.clone(name + "." + child.name, _this);
  31499. }
  31500. }
  31501. }
  31502. // Physics clone
  31503. var physicsEngine = _this.getScene().getPhysicsEngine();
  31504. if (clonePhysicsImpostor && physicsEngine) {
  31505. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31506. if (impostor) {
  31507. _this.physicsImpostor = impostor.clone(_this);
  31508. }
  31509. }
  31510. // Particles
  31511. for (index = 0; index < scene.particleSystems.length; index++) {
  31512. var system = scene.particleSystems[index];
  31513. if (system.emitter === source) {
  31514. system.clone(system.name, _this);
  31515. }
  31516. }
  31517. _this.refreshBoundingInfo();
  31518. _this.computeWorldMatrix(true);
  31519. }
  31520. // Parent
  31521. if (parent !== null) {
  31522. _this.parent = parent;
  31523. }
  31524. return _this;
  31525. }
  31526. Object.defineProperty(Mesh, "FRONTSIDE", {
  31527. /**
  31528. * Mesh side orientation : usually the external or front surface
  31529. */
  31530. get: function () {
  31531. return Mesh._FRONTSIDE;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Mesh, "BACKSIDE", {
  31537. /**
  31538. * Mesh side orientation : usually the internal or back surface
  31539. */
  31540. get: function () {
  31541. return Mesh._BACKSIDE;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31547. /**
  31548. * Mesh side orientation : both internal and external or front and back surfaces
  31549. */
  31550. get: function () {
  31551. return Mesh._DOUBLESIDE;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31557. /**
  31558. * Mesh side orientation : by default, `FRONTSIDE`
  31559. */
  31560. get: function () {
  31561. return Mesh._DEFAULTSIDE;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Mesh, "NO_CAP", {
  31567. /**
  31568. * Mesh cap setting : no cap
  31569. */
  31570. get: function () {
  31571. return Mesh._NO_CAP;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Mesh, "CAP_START", {
  31577. /**
  31578. * Mesh cap setting : one cap at the beginning of the mesh
  31579. */
  31580. get: function () {
  31581. return Mesh._CAP_START;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. Object.defineProperty(Mesh, "CAP_END", {
  31587. /**
  31588. * Mesh cap setting : one cap at the end of the mesh
  31589. */
  31590. get: function () {
  31591. return Mesh._CAP_END;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Mesh, "CAP_ALL", {
  31597. /**
  31598. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31599. */
  31600. get: function () {
  31601. return Mesh._CAP_ALL;
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31607. set: function (callback) {
  31608. if (this._onBeforeDrawObserver) {
  31609. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31610. }
  31611. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31612. },
  31613. enumerable: true,
  31614. configurable: true
  31615. });
  31616. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31617. get: function () {
  31618. return this._morphTargetManager;
  31619. },
  31620. set: function (value) {
  31621. if (this._morphTargetManager === value) {
  31622. return;
  31623. }
  31624. this._morphTargetManager = value;
  31625. this._syncGeometryWithMorphTargetManager();
  31626. },
  31627. enumerable: true,
  31628. configurable: true
  31629. });
  31630. Object.defineProperty(Mesh.prototype, "source", {
  31631. get: function () {
  31632. return this._source;
  31633. },
  31634. enumerable: true,
  31635. configurable: true
  31636. });
  31637. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31638. get: function () {
  31639. return this._unIndexed;
  31640. },
  31641. set: function (value) {
  31642. if (this._unIndexed !== value) {
  31643. this._unIndexed = value;
  31644. this._markSubMeshesAsAttributesDirty();
  31645. }
  31646. },
  31647. enumerable: true,
  31648. configurable: true
  31649. });
  31650. // Methods
  31651. /**
  31652. * Returns the string "Mesh".
  31653. */
  31654. Mesh.prototype.getClassName = function () {
  31655. return "Mesh";
  31656. };
  31657. /**
  31658. * Returns a string.
  31659. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31660. */
  31661. Mesh.prototype.toString = function (fullDetails) {
  31662. var ret = _super.prototype.toString.call(this, fullDetails);
  31663. ret += ", n vertices: " + this.getTotalVertices();
  31664. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31665. if (this.animations) {
  31666. for (var i = 0; i < this.animations.length; i++) {
  31667. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31668. }
  31669. }
  31670. if (fullDetails) {
  31671. if (this._geometry) {
  31672. var ib = this.getIndices();
  31673. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31674. if (vb && ib) {
  31675. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31676. }
  31677. }
  31678. else {
  31679. ret += ", flat shading: UNKNOWN";
  31680. }
  31681. }
  31682. return ret;
  31683. };
  31684. Mesh.prototype._unBindEffect = function () {
  31685. _super.prototype._unBindEffect.call(this);
  31686. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31687. var instance = _a[_i];
  31688. instance._unBindEffect();
  31689. }
  31690. };
  31691. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31692. /**
  31693. * True if the mesh has some Levels Of Details (LOD).
  31694. * Returns a boolean.
  31695. */
  31696. get: function () {
  31697. return this._LODLevels.length > 0;
  31698. },
  31699. enumerable: true,
  31700. configurable: true
  31701. });
  31702. /**
  31703. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31704. * @returns an array of {BABYLON.MeshLODLevel}
  31705. */
  31706. Mesh.prototype.getLODLevels = function () {
  31707. return this._LODLevels;
  31708. };
  31709. Mesh.prototype._sortLODLevels = function () {
  31710. this._LODLevels.sort(function (a, b) {
  31711. if (a.distance < b.distance) {
  31712. return 1;
  31713. }
  31714. if (a.distance > b.distance) {
  31715. return -1;
  31716. }
  31717. return 0;
  31718. });
  31719. };
  31720. /**
  31721. * Add a mesh as LOD level triggered at the given distance.
  31722. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31723. * @param distance The distance from the center of the object to show this level
  31724. * @param mesh The mesh to be added as LOD level (can be null)
  31725. * @return This mesh (for chaining)
  31726. */
  31727. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31728. if (mesh && mesh._masterMesh) {
  31729. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31730. return this;
  31731. }
  31732. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31733. this._LODLevels.push(level);
  31734. if (mesh) {
  31735. mesh._masterMesh = this;
  31736. }
  31737. this._sortLODLevels();
  31738. return this;
  31739. };
  31740. /**
  31741. * Returns the LOD level mesh at the passed distance or null if not found.
  31742. * It is related to the method `addLODLevel(distance, mesh)`.
  31743. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31744. * Returns an object Mesh or `null`.
  31745. */
  31746. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31747. for (var index = 0; index < this._LODLevels.length; index++) {
  31748. var level = this._LODLevels[index];
  31749. if (level.distance === distance) {
  31750. return level.mesh;
  31751. }
  31752. }
  31753. return null;
  31754. };
  31755. /**
  31756. * Remove a mesh from the LOD array
  31757. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31758. * @param {Mesh} mesh The mesh to be removed.
  31759. * @return {Mesh} This mesh (for chaining)
  31760. */
  31761. Mesh.prototype.removeLODLevel = function (mesh) {
  31762. for (var index = 0; index < this._LODLevels.length; index++) {
  31763. if (this._LODLevels[index].mesh === mesh) {
  31764. this._LODLevels.splice(index, 1);
  31765. if (mesh) {
  31766. mesh._masterMesh = null;
  31767. }
  31768. }
  31769. }
  31770. this._sortLODLevels();
  31771. return this;
  31772. };
  31773. /**
  31774. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31775. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31776. */
  31777. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31778. if (!this._LODLevels || this._LODLevels.length === 0) {
  31779. return this;
  31780. }
  31781. var bSphere;
  31782. if (boundingSphere) {
  31783. bSphere = boundingSphere;
  31784. }
  31785. else {
  31786. var boundingInfo = this.getBoundingInfo();
  31787. bSphere = boundingInfo.boundingSphere;
  31788. }
  31789. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31790. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31791. if (this.onLODLevelSelection) {
  31792. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31793. }
  31794. return this;
  31795. }
  31796. for (var index = 0; index < this._LODLevels.length; index++) {
  31797. var level = this._LODLevels[index];
  31798. if (level.distance < distanceToCamera) {
  31799. if (level.mesh) {
  31800. level.mesh._preActivate();
  31801. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31802. }
  31803. if (this.onLODLevelSelection) {
  31804. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31805. }
  31806. return level.mesh;
  31807. }
  31808. }
  31809. if (this.onLODLevelSelection) {
  31810. this.onLODLevelSelection(distanceToCamera, this, this);
  31811. }
  31812. return this;
  31813. };
  31814. Object.defineProperty(Mesh.prototype, "geometry", {
  31815. /**
  31816. * Returns the mesh internal Geometry object.
  31817. */
  31818. get: function () {
  31819. return this._geometry;
  31820. },
  31821. enumerable: true,
  31822. configurable: true
  31823. });
  31824. /**
  31825. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31826. */
  31827. Mesh.prototype.getTotalVertices = function () {
  31828. if (this._geometry === null || this._geometry === undefined) {
  31829. return 0;
  31830. }
  31831. return this._geometry.getTotalVertices();
  31832. };
  31833. /**
  31834. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31835. * 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.
  31836. * You can force the copy with forceCopy === true
  31837. * Returns null if the mesh has no geometry or no vertex buffer.
  31838. * Possible `kind` values :
  31839. * - BABYLON.VertexBuffer.PositionKind
  31840. * - BABYLON.VertexBuffer.UVKind
  31841. * - BABYLON.VertexBuffer.UV2Kind
  31842. * - BABYLON.VertexBuffer.UV3Kind
  31843. * - BABYLON.VertexBuffer.UV4Kind
  31844. * - BABYLON.VertexBuffer.UV5Kind
  31845. * - BABYLON.VertexBuffer.UV6Kind
  31846. * - BABYLON.VertexBuffer.ColorKind
  31847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31851. */
  31852. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31853. if (!this._geometry) {
  31854. return null;
  31855. }
  31856. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31857. };
  31858. /**
  31859. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31860. * Returns `null` if the mesh has no geometry.
  31861. * Possible `kind` values :
  31862. * - BABYLON.VertexBuffer.PositionKind
  31863. * - BABYLON.VertexBuffer.UVKind
  31864. * - BABYLON.VertexBuffer.UV2Kind
  31865. * - BABYLON.VertexBuffer.UV3Kind
  31866. * - BABYLON.VertexBuffer.UV4Kind
  31867. * - BABYLON.VertexBuffer.UV5Kind
  31868. * - BABYLON.VertexBuffer.UV6Kind
  31869. * - BABYLON.VertexBuffer.ColorKind
  31870. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31871. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31872. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31873. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31874. */
  31875. Mesh.prototype.getVertexBuffer = function (kind) {
  31876. if (!this._geometry) {
  31877. return null;
  31878. }
  31879. return this._geometry.getVertexBuffer(kind);
  31880. };
  31881. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31882. if (!this._geometry) {
  31883. if (this._delayInfo) {
  31884. return this._delayInfo.indexOf(kind) !== -1;
  31885. }
  31886. return false;
  31887. }
  31888. return this._geometry.isVerticesDataPresent(kind);
  31889. };
  31890. /**
  31891. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31892. * Possible `kind` values :
  31893. * - BABYLON.VertexBuffer.PositionKind
  31894. * - BABYLON.VertexBuffer.UVKind
  31895. * - BABYLON.VertexBuffer.UV2Kind
  31896. * - BABYLON.VertexBuffer.UV3Kind
  31897. * - BABYLON.VertexBuffer.UV4Kind
  31898. * - BABYLON.VertexBuffer.UV5Kind
  31899. * - BABYLON.VertexBuffer.UV6Kind
  31900. * - BABYLON.VertexBuffer.ColorKind
  31901. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31902. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31903. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31904. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31905. */
  31906. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31907. if (!this._geometry) {
  31908. if (this._delayInfo) {
  31909. return this._delayInfo.indexOf(kind) !== -1;
  31910. }
  31911. return false;
  31912. }
  31913. return this._geometry.isVertexBufferUpdatable(kind);
  31914. };
  31915. /**
  31916. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31917. * Possible `kind` values :
  31918. * - BABYLON.VertexBuffer.PositionKind
  31919. * - BABYLON.VertexBuffer.UVKind
  31920. * - BABYLON.VertexBuffer.UV2Kind
  31921. * - BABYLON.VertexBuffer.UV3Kind
  31922. * - BABYLON.VertexBuffer.UV4Kind
  31923. * - BABYLON.VertexBuffer.UV5Kind
  31924. * - BABYLON.VertexBuffer.UV6Kind
  31925. * - BABYLON.VertexBuffer.ColorKind
  31926. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31927. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31928. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31929. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31930. */
  31931. Mesh.prototype.getVerticesDataKinds = function () {
  31932. if (!this._geometry) {
  31933. var result = new Array();
  31934. if (this._delayInfo) {
  31935. this._delayInfo.forEach(function (kind, index, array) {
  31936. result.push(kind);
  31937. });
  31938. }
  31939. return result;
  31940. }
  31941. return this._geometry.getVerticesDataKinds();
  31942. };
  31943. /**
  31944. * Returns a positive integer : the total number of indices in this mesh geometry.
  31945. * Returns zero if the mesh has no geometry.
  31946. */
  31947. Mesh.prototype.getTotalIndices = function () {
  31948. if (!this._geometry) {
  31949. return 0;
  31950. }
  31951. return this._geometry.getTotalIndices();
  31952. };
  31953. /**
  31954. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31955. * If the parameter `copyWhenShared` is 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.
  31956. * Returns an empty array if the mesh has no geometry.
  31957. */
  31958. Mesh.prototype.getIndices = function (copyWhenShared) {
  31959. if (!this._geometry) {
  31960. return [];
  31961. }
  31962. return this._geometry.getIndices(copyWhenShared);
  31963. };
  31964. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31965. get: function () {
  31966. return this._masterMesh !== null && this._masterMesh !== undefined;
  31967. },
  31968. enumerable: true,
  31969. configurable: true
  31970. });
  31971. /**
  31972. * Determine if the current mesh is ready to be rendered
  31973. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31974. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31975. * @returns true if all associated assets are ready (material, textures, shaders)
  31976. */
  31977. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31978. if (completeCheck === void 0) { completeCheck = false; }
  31979. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31980. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31981. return false;
  31982. }
  31983. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31984. return false;
  31985. }
  31986. if (!this.subMeshes || this.subMeshes.length === 0) {
  31987. return true;
  31988. }
  31989. if (!completeCheck) {
  31990. return true;
  31991. }
  31992. var engine = this.getEngine();
  31993. var scene = this.getScene();
  31994. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31995. this.computeWorldMatrix();
  31996. var mat = this.material || scene.defaultMaterial;
  31997. if (mat) {
  31998. if (mat.storeEffectOnSubMeshes) {
  31999. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32000. var subMesh = _a[_i];
  32001. var effectiveMaterial = subMesh.getMaterial();
  32002. if (effectiveMaterial) {
  32003. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32004. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32005. return false;
  32006. }
  32007. }
  32008. else {
  32009. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32010. return false;
  32011. }
  32012. }
  32013. }
  32014. }
  32015. }
  32016. else {
  32017. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32018. return false;
  32019. }
  32020. }
  32021. }
  32022. // Shadows
  32023. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32024. var light = _c[_b];
  32025. var generator = light.getShadowGenerator();
  32026. if (generator) {
  32027. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32028. var subMesh = _e[_d];
  32029. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32030. return false;
  32031. }
  32032. }
  32033. }
  32034. }
  32035. // LOD
  32036. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32037. var lod = _g[_f];
  32038. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32039. return false;
  32040. }
  32041. }
  32042. return true;
  32043. };
  32044. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32045. /**
  32046. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32047. * This property is pertinent only for updatable parametric shapes.
  32048. */
  32049. get: function () {
  32050. return this._areNormalsFrozen;
  32051. },
  32052. enumerable: true,
  32053. configurable: true
  32054. });
  32055. /**
  32056. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32057. * It has no effect at all on other shapes.
  32058. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32059. * Returns the Mesh.
  32060. */
  32061. Mesh.prototype.freezeNormals = function () {
  32062. this._areNormalsFrozen = true;
  32063. return this;
  32064. };
  32065. /**
  32066. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32067. * It has no effect at all on other shapes.
  32068. * It reactivates the mesh normals computation if it was previously frozen.
  32069. * Returns the Mesh.
  32070. */
  32071. Mesh.prototype.unfreezeNormals = function () {
  32072. this._areNormalsFrozen = false;
  32073. return this;
  32074. };
  32075. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32076. /**
  32077. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32078. */
  32079. set: function (count) {
  32080. this._overridenInstanceCount = count;
  32081. },
  32082. enumerable: true,
  32083. configurable: true
  32084. });
  32085. // Methods
  32086. Mesh.prototype._preActivate = function () {
  32087. var sceneRenderId = this.getScene().getRenderId();
  32088. if (this._preActivateId === sceneRenderId) {
  32089. return this;
  32090. }
  32091. this._preActivateId = sceneRenderId;
  32092. this._visibleInstances = null;
  32093. return this;
  32094. };
  32095. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32096. if (this._visibleInstances) {
  32097. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32098. }
  32099. return this;
  32100. };
  32101. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32102. if (!this._visibleInstances) {
  32103. this._visibleInstances = {};
  32104. this._visibleInstances.defaultRenderId = renderId;
  32105. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32106. }
  32107. if (!this._visibleInstances[renderId]) {
  32108. this._visibleInstances[renderId] = new Array();
  32109. }
  32110. this._visibleInstances[renderId].push(instance);
  32111. return this;
  32112. };
  32113. /**
  32114. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32115. * This means the mesh underlying bounding box and sphere are recomputed.
  32116. * Returns the Mesh.
  32117. */
  32118. Mesh.prototype.refreshBoundingInfo = function () {
  32119. return this._refreshBoundingInfo(false);
  32120. };
  32121. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32122. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32123. return this;
  32124. }
  32125. var data = this._getPositionData(applySkeleton);
  32126. if (data) {
  32127. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32128. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32129. }
  32130. if (this.subMeshes) {
  32131. for (var index = 0; index < this.subMeshes.length; index++) {
  32132. this.subMeshes[index].refreshBoundingInfo();
  32133. }
  32134. }
  32135. this._updateBoundingInfo();
  32136. return this;
  32137. };
  32138. Mesh.prototype._getPositionData = function (applySkeleton) {
  32139. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32140. if (data && applySkeleton && this.skeleton) {
  32141. data = BABYLON.Tools.Slice(data);
  32142. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32143. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32144. if (matricesWeightsData && matricesIndicesData) {
  32145. var needExtras = this.numBoneInfluencers > 4;
  32146. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32147. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32148. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32149. var tempVector = BABYLON.Tmp.Vector3[0];
  32150. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32151. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32152. var matWeightIdx = 0;
  32153. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32154. finalMatrix.reset();
  32155. var inf;
  32156. var weight;
  32157. for (inf = 0; inf < 4; inf++) {
  32158. weight = matricesWeightsData[matWeightIdx + inf];
  32159. if (weight <= 0)
  32160. break;
  32161. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32162. finalMatrix.addToSelf(tempMatrix);
  32163. }
  32164. if (needExtras) {
  32165. for (inf = 0; inf < 4; inf++) {
  32166. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32167. if (weight <= 0)
  32168. break;
  32169. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32170. finalMatrix.addToSelf(tempMatrix);
  32171. }
  32172. }
  32173. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32174. tempVector.toArray(data, index);
  32175. }
  32176. }
  32177. }
  32178. return data;
  32179. };
  32180. Mesh.prototype._createGlobalSubMesh = function (force) {
  32181. var totalVertices = this.getTotalVertices();
  32182. if (!totalVertices || !this.getIndices()) {
  32183. return null;
  32184. }
  32185. // Check if we need to recreate the submeshes
  32186. if (this.subMeshes && this.subMeshes.length > 0) {
  32187. var ib = this.getIndices();
  32188. if (!ib) {
  32189. return null;
  32190. }
  32191. var totalIndices = ib.length;
  32192. var needToRecreate = false;
  32193. if (force) {
  32194. needToRecreate = true;
  32195. }
  32196. else {
  32197. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32198. var submesh = _a[_i];
  32199. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32200. needToRecreate = true;
  32201. break;
  32202. }
  32203. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32204. needToRecreate = true;
  32205. break;
  32206. }
  32207. }
  32208. }
  32209. if (!needToRecreate) {
  32210. return this.subMeshes[0];
  32211. }
  32212. }
  32213. this.releaseSubMeshes();
  32214. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32215. };
  32216. Mesh.prototype.subdivide = function (count) {
  32217. if (count < 1) {
  32218. return;
  32219. }
  32220. var totalIndices = this.getTotalIndices();
  32221. var subdivisionSize = (totalIndices / count) | 0;
  32222. var offset = 0;
  32223. // Ensure that subdivisionSize is a multiple of 3
  32224. while (subdivisionSize % 3 !== 0) {
  32225. subdivisionSize++;
  32226. }
  32227. this.releaseSubMeshes();
  32228. for (var index = 0; index < count; index++) {
  32229. if (offset >= totalIndices) {
  32230. break;
  32231. }
  32232. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32233. offset += subdivisionSize;
  32234. }
  32235. this.synchronizeInstances();
  32236. };
  32237. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32238. if (updatable === void 0) { updatable = false; }
  32239. if (!this._geometry) {
  32240. var vertexData = new BABYLON.VertexData();
  32241. vertexData.set(data, kind);
  32242. var scene = this.getScene();
  32243. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32244. }
  32245. else {
  32246. this._geometry.setVerticesData(kind, data, updatable, stride);
  32247. }
  32248. return this;
  32249. };
  32250. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32251. if (updatable === void 0) { updatable = true; }
  32252. var vb = this.getVertexBuffer(kind);
  32253. if (!vb || vb.isUpdatable() === updatable) {
  32254. return;
  32255. }
  32256. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32257. };
  32258. /**
  32259. * Sets the mesh VertexBuffer.
  32260. * Returns the Mesh.
  32261. */
  32262. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32263. if (!this._geometry) {
  32264. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32265. }
  32266. this._geometry.setVerticesBuffer(buffer);
  32267. return this;
  32268. };
  32269. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32270. if (!this._geometry) {
  32271. return this;
  32272. }
  32273. if (!makeItUnique) {
  32274. this._geometry.updateVerticesData(kind, data, updateExtends);
  32275. }
  32276. else {
  32277. this.makeGeometryUnique();
  32278. this.updateVerticesData(kind, data, updateExtends, false);
  32279. }
  32280. return this;
  32281. };
  32282. /**
  32283. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32284. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32285. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32286. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32287. * Returns the Mesh.
  32288. */
  32289. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32290. if (computeNormals === void 0) { computeNormals = true; }
  32291. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32292. if (!positions) {
  32293. return this;
  32294. }
  32295. positionFunction(positions);
  32296. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32297. if (computeNormals) {
  32298. var indices = this.getIndices();
  32299. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32300. if (!normals) {
  32301. return this;
  32302. }
  32303. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32304. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32305. }
  32306. return this;
  32307. };
  32308. /**
  32309. * Creates a un-shared specific occurence of the geometry for the mesh.
  32310. * Returns the Mesh.
  32311. */
  32312. Mesh.prototype.makeGeometryUnique = function () {
  32313. if (!this._geometry) {
  32314. return this;
  32315. }
  32316. var oldGeometry = this._geometry;
  32317. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32318. oldGeometry.releaseForMesh(this, true);
  32319. geometry.applyToMesh(this);
  32320. return this;
  32321. };
  32322. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32323. if (totalVertices === void 0) { totalVertices = null; }
  32324. if (updatable === void 0) { updatable = false; }
  32325. if (!this._geometry) {
  32326. var vertexData = new BABYLON.VertexData();
  32327. vertexData.indices = indices;
  32328. var scene = this.getScene();
  32329. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32330. }
  32331. else {
  32332. this._geometry.setIndices(indices, totalVertices, updatable);
  32333. }
  32334. return this;
  32335. };
  32336. /**
  32337. * Update the current index buffer
  32338. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32339. * Returns the Mesh.
  32340. */
  32341. Mesh.prototype.updateIndices = function (indices, offset) {
  32342. if (!this._geometry) {
  32343. return this;
  32344. }
  32345. this._geometry.updateIndices(indices, offset);
  32346. return this;
  32347. };
  32348. /**
  32349. * Invert the geometry to move from a right handed system to a left handed one.
  32350. * Returns the Mesh.
  32351. */
  32352. Mesh.prototype.toLeftHanded = function () {
  32353. if (!this._geometry) {
  32354. return this;
  32355. }
  32356. this._geometry.toLeftHanded();
  32357. return this;
  32358. };
  32359. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32360. if (!this._geometry) {
  32361. return this;
  32362. }
  32363. var engine = this.getScene().getEngine();
  32364. // Wireframe
  32365. var indexToBind;
  32366. if (this._unIndexed) {
  32367. indexToBind = null;
  32368. }
  32369. else {
  32370. switch (fillMode) {
  32371. case BABYLON.Material.PointFillMode:
  32372. indexToBind = null;
  32373. break;
  32374. case BABYLON.Material.WireFrameFillMode:
  32375. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32376. break;
  32377. default:
  32378. case BABYLON.Material.TriangleFillMode:
  32379. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32380. break;
  32381. }
  32382. }
  32383. // VBOs
  32384. this._geometry._bind(effect, indexToBind);
  32385. return this;
  32386. };
  32387. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32388. if (alternate === void 0) { alternate = false; }
  32389. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32390. return this;
  32391. }
  32392. this.onBeforeDrawObservable.notifyObservers(this);
  32393. var scene = this.getScene();
  32394. var engine = scene.getEngine();
  32395. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32396. // or triangles as points
  32397. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32398. }
  32399. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32400. // Triangles as wireframe
  32401. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32402. }
  32403. else {
  32404. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32405. }
  32406. if (scene._isAlternateRenderingEnabled && !alternate) {
  32407. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32408. if (!effect || !scene.activeCamera) {
  32409. return this;
  32410. }
  32411. scene._switchToAlternateCameraConfiguration(true);
  32412. this._effectiveMaterial.bindView(effect);
  32413. this._effectiveMaterial.bindViewProjection(effect);
  32414. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32415. this._draw(subMesh, fillMode, instancesCount, true);
  32416. engine.setViewport(scene.activeCamera.viewport);
  32417. scene._switchToAlternateCameraConfiguration(false);
  32418. this._effectiveMaterial.bindView(effect);
  32419. this._effectiveMaterial.bindViewProjection(effect);
  32420. }
  32421. return this;
  32422. };
  32423. /**
  32424. * Registers for this mesh a javascript function called just before the rendering process.
  32425. * This function is passed the current mesh.
  32426. * Return the Mesh.
  32427. */
  32428. Mesh.prototype.registerBeforeRender = function (func) {
  32429. this.onBeforeRenderObservable.add(func);
  32430. return this;
  32431. };
  32432. /**
  32433. * Disposes a previously registered javascript function called before the rendering.
  32434. * This function is passed the current mesh.
  32435. * Returns the Mesh.
  32436. */
  32437. Mesh.prototype.unregisterBeforeRender = function (func) {
  32438. this.onBeforeRenderObservable.removeCallback(func);
  32439. return this;
  32440. };
  32441. /**
  32442. * Registers for this mesh a javascript function called just after the rendering is complete.
  32443. * This function is passed the current mesh.
  32444. * Returns the Mesh.
  32445. */
  32446. Mesh.prototype.registerAfterRender = function (func) {
  32447. this.onAfterRenderObservable.add(func);
  32448. return this;
  32449. };
  32450. /**
  32451. * Disposes a previously registered javascript function called after the rendering.
  32452. * This function is passed the current mesh.
  32453. * Return the Mesh.
  32454. */
  32455. Mesh.prototype.unregisterAfterRender = function (func) {
  32456. this.onAfterRenderObservable.removeCallback(func);
  32457. return this;
  32458. };
  32459. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32460. var scene = this.getScene();
  32461. this._batchCache.mustReturn = false;
  32462. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32463. this._batchCache.visibleInstances[subMeshId] = null;
  32464. if (this._visibleInstances) {
  32465. var currentRenderId = scene.getRenderId();
  32466. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32467. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32468. var selfRenderId = this._renderId;
  32469. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32470. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32471. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32472. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32473. }
  32474. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32475. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32476. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32477. this._batchCache.mustReturn = true;
  32478. return this._batchCache;
  32479. }
  32480. if (currentRenderId !== selfRenderId) {
  32481. this._batchCache.renderSelf[subMeshId] = false;
  32482. }
  32483. }
  32484. this._renderIdForInstances[subMeshId] = currentRenderId;
  32485. }
  32486. return this._batchCache;
  32487. };
  32488. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32489. var visibleInstances = batch.visibleInstances[subMesh._id];
  32490. if (!visibleInstances) {
  32491. return this;
  32492. }
  32493. var matricesCount = visibleInstances.length + 1;
  32494. var bufferSize = matricesCount * 16 * 4;
  32495. var currentInstancesBufferSize = this._instancesBufferSize;
  32496. var instancesBuffer = this._instancesBuffer;
  32497. while (this._instancesBufferSize < bufferSize) {
  32498. this._instancesBufferSize *= 2;
  32499. }
  32500. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32501. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32502. }
  32503. var offset = 0;
  32504. var instancesCount = 0;
  32505. var world = this.getWorldMatrix();
  32506. if (batch.renderSelf[subMesh._id]) {
  32507. world.copyToArray(this._instancesData, offset);
  32508. offset += 16;
  32509. instancesCount++;
  32510. }
  32511. if (visibleInstances) {
  32512. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32513. var instance = visibleInstances[instanceIndex];
  32514. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32515. offset += 16;
  32516. instancesCount++;
  32517. }
  32518. }
  32519. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32520. if (instancesBuffer) {
  32521. instancesBuffer.dispose();
  32522. }
  32523. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32524. this._instancesBuffer = instancesBuffer;
  32525. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32526. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32527. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32528. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32529. }
  32530. else {
  32531. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32532. }
  32533. this._bind(subMesh, effect, fillMode);
  32534. this._draw(subMesh, fillMode, instancesCount);
  32535. engine.unbindInstanceAttributes();
  32536. return this;
  32537. };
  32538. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32539. var scene = this.getScene();
  32540. var engine = scene.getEngine();
  32541. if (hardwareInstancedRendering) {
  32542. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32543. }
  32544. else {
  32545. if (batch.renderSelf[subMesh._id]) {
  32546. // Draw
  32547. if (onBeforeDraw) {
  32548. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32549. }
  32550. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32551. }
  32552. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32553. if (visibleInstancesForSubMesh) {
  32554. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32555. var instance = visibleInstancesForSubMesh[instanceIndex];
  32556. // World
  32557. var world = instance.getWorldMatrix();
  32558. if (onBeforeDraw) {
  32559. onBeforeDraw(true, world, effectiveMaterial);
  32560. }
  32561. // Draw
  32562. this._draw(subMesh, fillMode);
  32563. }
  32564. }
  32565. }
  32566. return this;
  32567. };
  32568. /**
  32569. * 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
  32570. * @param subMesh defines the subMesh to render
  32571. * @param enableAlphaMode defines if alpha mode can be changed
  32572. * @returns the current mesh
  32573. */
  32574. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32575. this._checkOcclusionQuery();
  32576. if (this._isOccluded) {
  32577. return this;
  32578. }
  32579. var scene = this.getScene();
  32580. // Managing instances
  32581. var batch = this._getInstancesRenderList(subMesh._id);
  32582. if (batch.mustReturn) {
  32583. return this;
  32584. }
  32585. // Checking geometry state
  32586. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32587. return this;
  32588. }
  32589. this.onBeforeRenderObservable.notifyObservers(this);
  32590. var engine = scene.getEngine();
  32591. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32592. // Material
  32593. var material = subMesh.getMaterial();
  32594. if (!material) {
  32595. return this;
  32596. }
  32597. this._effectiveMaterial = material;
  32598. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32599. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32600. return this;
  32601. }
  32602. }
  32603. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32604. return this;
  32605. }
  32606. // Alpha mode
  32607. if (enableAlphaMode) {
  32608. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32609. }
  32610. // Outline - step 1
  32611. var savedDepthWrite = engine.getDepthWrite();
  32612. if (this.renderOutline) {
  32613. engine.setDepthWrite(false);
  32614. scene.getOutlineRenderer().render(subMesh, batch);
  32615. engine.setDepthWrite(savedDepthWrite);
  32616. }
  32617. var effect;
  32618. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32619. effect = subMesh.effect;
  32620. }
  32621. else {
  32622. effect = this._effectiveMaterial.getEffect();
  32623. }
  32624. if (!effect) {
  32625. return this;
  32626. }
  32627. var sideOrientation = this.overrideMaterialSideOrientation;
  32628. if (sideOrientation == null) {
  32629. sideOrientation = this._effectiveMaterial.sideOrientation;
  32630. if (this._getWorldMatrixDeterminant() < 0) {
  32631. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32632. }
  32633. }
  32634. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32635. if (this._effectiveMaterial.forceDepthWrite) {
  32636. engine.setDepthWrite(true);
  32637. }
  32638. // Bind
  32639. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32640. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32641. this._bind(subMesh, effect, fillMode);
  32642. }
  32643. var world = this.getWorldMatrix();
  32644. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32645. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32646. }
  32647. else {
  32648. this._effectiveMaterial.bind(world, this);
  32649. }
  32650. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32651. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32652. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32653. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32654. }
  32655. // Draw
  32656. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32657. // Unbind
  32658. this._effectiveMaterial.unbind();
  32659. // Outline - step 2
  32660. if (this.renderOutline && savedDepthWrite) {
  32661. engine.setDepthWrite(true);
  32662. engine.setColorWrite(false);
  32663. scene.getOutlineRenderer().render(subMesh, batch);
  32664. engine.setColorWrite(true);
  32665. }
  32666. // Overlay
  32667. if (this.renderOverlay) {
  32668. var currentMode = engine.getAlphaMode();
  32669. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32670. scene.getOutlineRenderer().render(subMesh, batch, true);
  32671. engine.setAlphaMode(currentMode);
  32672. }
  32673. this.onAfterRenderObservable.notifyObservers(this);
  32674. return this;
  32675. };
  32676. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32677. if (isInstance && effectiveMaterial) {
  32678. effectiveMaterial.bindOnlyWorldMatrix(world);
  32679. }
  32680. };
  32681. /**
  32682. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32683. */
  32684. Mesh.prototype.getEmittedParticleSystems = function () {
  32685. var results = new Array();
  32686. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32687. var particleSystem = this.getScene().particleSystems[index];
  32688. if (particleSystem.emitter === this) {
  32689. results.push(particleSystem);
  32690. }
  32691. }
  32692. return results;
  32693. };
  32694. /**
  32695. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32696. */
  32697. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32698. var results = new Array();
  32699. var descendants = this.getDescendants();
  32700. descendants.push(this);
  32701. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32702. var particleSystem = this.getScene().particleSystems[index];
  32703. var emitter = particleSystem.emitter;
  32704. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32705. results.push(particleSystem);
  32706. }
  32707. }
  32708. return results;
  32709. };
  32710. /**
  32711. * Normalize matrix weights so that all vertices have a total weight set to 1
  32712. */
  32713. Mesh.prototype.cleanMatrixWeights = function () {
  32714. var epsilon = 1e-3;
  32715. var noInfluenceBoneIndex = 0.0;
  32716. if (this.skeleton) {
  32717. noInfluenceBoneIndex = this.skeleton.bones.length;
  32718. }
  32719. else {
  32720. return;
  32721. }
  32722. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32723. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32724. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32725. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32726. var influencers = this.numBoneInfluencers;
  32727. var size = matricesWeights.length;
  32728. for (var i = 0; i < size; i += 4) {
  32729. var weight = 0.0;
  32730. var firstZeroWeight = -1;
  32731. for (var j = 0; j < 4; j++) {
  32732. var w = matricesWeights[i + j];
  32733. weight += w;
  32734. if (w < epsilon && firstZeroWeight < 0) {
  32735. firstZeroWeight = j;
  32736. }
  32737. }
  32738. if (matricesWeightsExtra) {
  32739. for (var j = 0; j < 4; j++) {
  32740. var w = matricesWeightsExtra[i + j];
  32741. weight += w;
  32742. if (w < epsilon && firstZeroWeight < 0) {
  32743. firstZeroWeight = j + 4;
  32744. }
  32745. }
  32746. }
  32747. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32748. firstZeroWeight = influencers - 1;
  32749. }
  32750. if (weight > epsilon) {
  32751. var mweight = 1.0 / weight;
  32752. for (var j = 0; j < 4; j++) {
  32753. matricesWeights[i + j] *= mweight;
  32754. }
  32755. if (matricesWeightsExtra) {
  32756. for (var j = 0; j < 4; j++) {
  32757. matricesWeightsExtra[i + j] *= mweight;
  32758. }
  32759. }
  32760. }
  32761. else {
  32762. if (firstZeroWeight >= 4) {
  32763. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32764. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32765. }
  32766. else {
  32767. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32768. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32769. }
  32770. }
  32771. }
  32772. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32773. if (matricesIndicesExtra) {
  32774. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32775. }
  32776. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32777. if (matricesWeightsExtra) {
  32778. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32779. }
  32780. };
  32781. Mesh.prototype._checkDelayState = function () {
  32782. var scene = this.getScene();
  32783. if (this._geometry) {
  32784. this._geometry.load(scene);
  32785. }
  32786. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32787. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32788. this._queueLoad(scene);
  32789. }
  32790. return this;
  32791. };
  32792. Mesh.prototype._queueLoad = function (scene) {
  32793. var _this = this;
  32794. scene._addPendingData(this);
  32795. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32796. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32797. if (data instanceof ArrayBuffer) {
  32798. _this._delayLoadingFunction(data, _this);
  32799. }
  32800. else {
  32801. _this._delayLoadingFunction(JSON.parse(data), _this);
  32802. }
  32803. _this.instances.forEach(function (instance) {
  32804. instance._syncSubMeshes();
  32805. });
  32806. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32807. scene._removePendingData(_this);
  32808. }, function () { }, scene.database, getBinaryData);
  32809. return this;
  32810. };
  32811. /**
  32812. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32813. */
  32814. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32815. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32816. return false;
  32817. }
  32818. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32819. return false;
  32820. }
  32821. this._checkDelayState();
  32822. return true;
  32823. };
  32824. /**
  32825. * Sets the mesh material by the material or multiMaterial `id` property.
  32826. * The material `id` is a string identifying the material or the multiMaterial.
  32827. * This method returns the Mesh.
  32828. */
  32829. Mesh.prototype.setMaterialByID = function (id) {
  32830. var materials = this.getScene().materials;
  32831. var index;
  32832. for (index = materials.length - 1; index > -1; index--) {
  32833. if (materials[index].id === id) {
  32834. this.material = materials[index];
  32835. return this;
  32836. }
  32837. }
  32838. // Multi
  32839. var multiMaterials = this.getScene().multiMaterials;
  32840. for (index = multiMaterials.length - 1; index > -1; index--) {
  32841. if (multiMaterials[index].id === id) {
  32842. this.material = multiMaterials[index];
  32843. return this;
  32844. }
  32845. }
  32846. return this;
  32847. };
  32848. /**
  32849. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32850. */
  32851. Mesh.prototype.getAnimatables = function () {
  32852. var results = new Array();
  32853. if (this.material) {
  32854. results.push(this.material);
  32855. }
  32856. if (this.skeleton) {
  32857. results.push(this.skeleton);
  32858. }
  32859. return results;
  32860. };
  32861. /**
  32862. * Modifies the mesh geometry according to the passed transformation matrix.
  32863. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32864. * The mesh normals are modified accordingly the same transformation.
  32865. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32866. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32867. * Returns the Mesh.
  32868. */
  32869. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32870. // Position
  32871. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32872. return this;
  32873. }
  32874. var submeshes = this.subMeshes.splice(0);
  32875. this._resetPointsArrayCache();
  32876. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32877. var temp = new Array();
  32878. var index;
  32879. for (index = 0; index < data.length; index += 3) {
  32880. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32881. }
  32882. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32883. // Normals
  32884. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32885. return this;
  32886. }
  32887. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32888. temp = [];
  32889. for (index = 0; index < data.length; index += 3) {
  32890. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32891. }
  32892. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32893. // flip faces?
  32894. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32895. this.flipFaces();
  32896. }
  32897. // Restore submeshes
  32898. this.releaseSubMeshes();
  32899. this.subMeshes = submeshes;
  32900. return this;
  32901. };
  32902. /**
  32903. * Modifies the mesh geometry according to its own current World Matrix.
  32904. * The mesh World Matrix is then reset.
  32905. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32906. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32907. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32908. * Returns the Mesh.
  32909. */
  32910. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32911. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32912. this.scaling.copyFromFloats(1, 1, 1);
  32913. this.position.copyFromFloats(0, 0, 0);
  32914. this.rotation.copyFromFloats(0, 0, 0);
  32915. //only if quaternion is already set
  32916. if (this.rotationQuaternion) {
  32917. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32918. }
  32919. this._worldMatrix = BABYLON.Matrix.Identity();
  32920. return this;
  32921. };
  32922. Object.defineProperty(Mesh.prototype, "_positions", {
  32923. // Cache
  32924. get: function () {
  32925. if (this._geometry) {
  32926. return this._geometry._positions;
  32927. }
  32928. return null;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Mesh.prototype._resetPointsArrayCache = function () {
  32934. if (this._geometry) {
  32935. this._geometry._resetPointsArrayCache();
  32936. }
  32937. return this;
  32938. };
  32939. Mesh.prototype._generatePointsArray = function () {
  32940. if (this._geometry) {
  32941. return this._geometry._generatePointsArray();
  32942. }
  32943. return false;
  32944. };
  32945. /**
  32946. * Returns a new Mesh object generated from the current mesh properties.
  32947. * This method must not get confused with createInstance().
  32948. * The parameter `name` is a string, the name given to the new mesh.
  32949. * The optional parameter `newParent` can be any Node object (default `null`).
  32950. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32951. * 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.
  32952. */
  32953. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32954. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32955. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32956. };
  32957. /**
  32958. * Releases resources associated with this mesh.
  32959. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32960. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32961. */
  32962. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32963. var _this = this;
  32964. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32965. this.morphTargetManager = null;
  32966. if (this._geometry) {
  32967. this._geometry.releaseForMesh(this, true);
  32968. }
  32969. // Sources
  32970. var meshes = this.getScene().meshes;
  32971. meshes.forEach(function (abstractMesh) {
  32972. var mesh = abstractMesh;
  32973. if (mesh._source && mesh._source === _this) {
  32974. mesh._source = null;
  32975. }
  32976. });
  32977. this._source = null;
  32978. // Instances
  32979. if (this._instancesBuffer) {
  32980. this._instancesBuffer.dispose();
  32981. this._instancesBuffer = null;
  32982. }
  32983. while (this.instances.length) {
  32984. this.instances[0].dispose();
  32985. }
  32986. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32987. };
  32988. /**
  32989. * Modifies the mesh geometry according to a displacement map.
  32990. * 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.
  32991. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32992. * This method returns nothing.
  32993. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32994. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32995. * The parameter `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.
  32996. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32997. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32998. *
  32999. * Returns the Mesh.
  33000. */
  33001. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33002. var _this = this;
  33003. var scene = this.getScene();
  33004. var onload = function (img) {
  33005. // Getting height map data
  33006. var canvas = document.createElement("canvas");
  33007. var context = canvas.getContext("2d");
  33008. var heightMapWidth = img.width;
  33009. var heightMapHeight = img.height;
  33010. canvas.width = heightMapWidth;
  33011. canvas.height = heightMapHeight;
  33012. context.drawImage(img, 0, 0);
  33013. // Create VertexData from map data
  33014. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33015. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33016. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33017. //execute success callback, if set
  33018. if (onSuccess) {
  33019. onSuccess(_this);
  33020. }
  33021. };
  33022. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33023. return this;
  33024. };
  33025. /**
  33026. * Modifies the mesh geometry according to a displacementMap buffer.
  33027. * 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.
  33028. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33029. * This method returns nothing.
  33030. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33031. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33032. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33033. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33034. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33035. *
  33036. * Returns the Mesh.
  33037. */
  33038. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33039. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33040. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33041. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33042. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33043. return this;
  33044. }
  33045. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33046. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33047. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33048. var position = BABYLON.Vector3.Zero();
  33049. var normal = BABYLON.Vector3.Zero();
  33050. var uv = BABYLON.Vector2.Zero();
  33051. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33052. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33053. for (var index = 0; index < positions.length; index += 3) {
  33054. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33055. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33056. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33057. // Compute height
  33058. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33059. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33060. var pos = (u + v * heightMapWidth) * 4;
  33061. var r = buffer[pos] / 255.0;
  33062. var g = buffer[pos + 1] / 255.0;
  33063. var b = buffer[pos + 2] / 255.0;
  33064. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33065. normal.normalize();
  33066. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33067. position = position.add(normal);
  33068. position.toArray(positions, index);
  33069. }
  33070. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33071. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33072. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33073. return this;
  33074. };
  33075. /**
  33076. * Modify the mesh to get a flat shading rendering.
  33077. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33078. * This method returns the Mesh.
  33079. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33080. */
  33081. Mesh.prototype.convertToFlatShadedMesh = function () {
  33082. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33083. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33084. var kinds = this.getVerticesDataKinds();
  33085. var vbs = {};
  33086. var data = {};
  33087. var newdata = {};
  33088. var updatableNormals = false;
  33089. var kindIndex;
  33090. var kind;
  33091. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33092. kind = kinds[kindIndex];
  33093. var vertexBuffer = this.getVertexBuffer(kind);
  33094. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33095. updatableNormals = vertexBuffer.isUpdatable();
  33096. kinds.splice(kindIndex, 1);
  33097. kindIndex--;
  33098. continue;
  33099. }
  33100. vbs[kind] = vertexBuffer;
  33101. data[kind] = vbs[kind].getData();
  33102. newdata[kind] = [];
  33103. }
  33104. // Save previous submeshes
  33105. var previousSubmeshes = this.subMeshes.slice(0);
  33106. var indices = this.getIndices();
  33107. var totalIndices = this.getTotalIndices();
  33108. // Generating unique vertices per face
  33109. var index;
  33110. for (index = 0; index < totalIndices; index++) {
  33111. var vertexIndex = indices[index];
  33112. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33113. kind = kinds[kindIndex];
  33114. var stride = vbs[kind].getStrideSize();
  33115. for (var offset = 0; offset < stride; offset++) {
  33116. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33117. }
  33118. }
  33119. }
  33120. // Updating faces & normal
  33121. var normals = [];
  33122. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33123. for (index = 0; index < totalIndices; index += 3) {
  33124. indices[index] = index;
  33125. indices[index + 1] = index + 1;
  33126. indices[index + 2] = index + 2;
  33127. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33128. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33129. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33130. var p1p2 = p1.subtract(p2);
  33131. var p3p2 = p3.subtract(p2);
  33132. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33133. // Store same normals for every vertex
  33134. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33135. normals.push(normal.x);
  33136. normals.push(normal.y);
  33137. normals.push(normal.z);
  33138. }
  33139. }
  33140. this.setIndices(indices);
  33141. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33142. // Updating vertex buffers
  33143. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33144. kind = kinds[kindIndex];
  33145. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33146. }
  33147. // Updating submeshes
  33148. this.releaseSubMeshes();
  33149. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33150. var previousOne = previousSubmeshes[submeshIndex];
  33151. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33152. }
  33153. this.synchronizeInstances();
  33154. return this;
  33155. };
  33156. /**
  33157. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33158. * In other words, more vertices, no more indices and a single bigger VBO.
  33159. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33160. * Returns the Mesh.
  33161. */
  33162. Mesh.prototype.convertToUnIndexedMesh = function () {
  33163. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33164. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33165. var kinds = this.getVerticesDataKinds();
  33166. var vbs = {};
  33167. var data = {};
  33168. var newdata = {};
  33169. var kindIndex;
  33170. var kind;
  33171. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33172. kind = kinds[kindIndex];
  33173. var vertexBuffer = this.getVertexBuffer(kind);
  33174. vbs[kind] = vertexBuffer;
  33175. data[kind] = vbs[kind].getData();
  33176. newdata[kind] = [];
  33177. }
  33178. // Save previous submeshes
  33179. var previousSubmeshes = this.subMeshes.slice(0);
  33180. var indices = this.getIndices();
  33181. var totalIndices = this.getTotalIndices();
  33182. // Generating unique vertices per face
  33183. var index;
  33184. for (index = 0; index < totalIndices; index++) {
  33185. var vertexIndex = indices[index];
  33186. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33187. kind = kinds[kindIndex];
  33188. var stride = vbs[kind].getStrideSize();
  33189. for (var offset = 0; offset < stride; offset++) {
  33190. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33191. }
  33192. }
  33193. }
  33194. // Updating indices
  33195. for (index = 0; index < totalIndices; index += 3) {
  33196. indices[index] = index;
  33197. indices[index + 1] = index + 1;
  33198. indices[index + 2] = index + 2;
  33199. }
  33200. this.setIndices(indices);
  33201. // Updating vertex buffers
  33202. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33203. kind = kinds[kindIndex];
  33204. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33205. }
  33206. // Updating submeshes
  33207. this.releaseSubMeshes();
  33208. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33209. var previousOne = previousSubmeshes[submeshIndex];
  33210. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33211. }
  33212. this._unIndexed = true;
  33213. this.synchronizeInstances();
  33214. return this;
  33215. };
  33216. /**
  33217. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33218. * This method returns the Mesh.
  33219. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33220. */
  33221. Mesh.prototype.flipFaces = function (flipNormals) {
  33222. if (flipNormals === void 0) { flipNormals = false; }
  33223. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33224. var i;
  33225. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33226. for (i = 0; i < vertex_data.normals.length; i++) {
  33227. vertex_data.normals[i] *= -1;
  33228. }
  33229. }
  33230. if (vertex_data.indices) {
  33231. var temp;
  33232. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33233. // reassign indices
  33234. temp = vertex_data.indices[i + 1];
  33235. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33236. vertex_data.indices[i + 2] = temp;
  33237. }
  33238. }
  33239. vertex_data.applyToMesh(this);
  33240. return this;
  33241. };
  33242. // Instances
  33243. /**
  33244. * Creates a new InstancedMesh object from the mesh model.
  33245. * An instance shares the same properties and the same material than its model.
  33246. * Only these properties of each instance can then be set individually :
  33247. * - position
  33248. * - rotation
  33249. * - rotationQuaternion
  33250. * - setPivotMatrix
  33251. * - scaling
  33252. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33253. * Warning : this method is not supported for Line mesh and LineSystem
  33254. */
  33255. Mesh.prototype.createInstance = function (name) {
  33256. return new BABYLON.InstancedMesh(name, this);
  33257. };
  33258. /**
  33259. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33260. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33261. * This method returns the Mesh.
  33262. */
  33263. Mesh.prototype.synchronizeInstances = function () {
  33264. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33265. var instance = this.instances[instanceIndex];
  33266. instance._syncSubMeshes();
  33267. }
  33268. return this;
  33269. };
  33270. /**
  33271. * Simplify the mesh according to the given array of settings.
  33272. * Function will return immediately and will simplify async. It returns the Mesh.
  33273. * @param settings a collection of simplification settings.
  33274. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33275. * @param type the type of simplification to run.
  33276. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33277. */
  33278. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33279. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33280. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33281. this.getScene().simplificationQueue.addTask({
  33282. settings: settings,
  33283. parallelProcessing: parallelProcessing,
  33284. mesh: this,
  33285. simplificationType: simplificationType,
  33286. successCallback: successCallback
  33287. });
  33288. return this;
  33289. };
  33290. /**
  33291. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33292. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33293. * This should be used together with the simplification to avoid disappearing triangles.
  33294. * Returns the Mesh.
  33295. * @param successCallback an optional success callback to be called after the optimization finished.
  33296. */
  33297. Mesh.prototype.optimizeIndices = function (successCallback) {
  33298. var _this = this;
  33299. var indices = this.getIndices();
  33300. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33301. if (!positions || !indices) {
  33302. return this;
  33303. }
  33304. var vectorPositions = new Array();
  33305. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33306. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33307. }
  33308. var dupes = new Array();
  33309. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33310. var realPos = vectorPositions.length - 1 - iteration;
  33311. var testedPosition = vectorPositions[realPos];
  33312. for (var j = 0; j < realPos; ++j) {
  33313. var againstPosition = vectorPositions[j];
  33314. if (testedPosition.equals(againstPosition)) {
  33315. dupes[realPos] = j;
  33316. break;
  33317. }
  33318. }
  33319. }, function () {
  33320. for (var i = 0; i < indices.length; ++i) {
  33321. indices[i] = dupes[indices[i]] || indices[i];
  33322. }
  33323. //indices are now reordered
  33324. var originalSubMeshes = _this.subMeshes.slice(0);
  33325. _this.setIndices(indices);
  33326. _this.subMeshes = originalSubMeshes;
  33327. if (successCallback) {
  33328. successCallback(_this);
  33329. }
  33330. });
  33331. return this;
  33332. };
  33333. Mesh.prototype.serialize = function (serializationObject) {
  33334. serializationObject.name = this.name;
  33335. serializationObject.id = this.id;
  33336. serializationObject.type = this.getClassName();
  33337. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33338. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33339. }
  33340. serializationObject.position = this.position.asArray();
  33341. if (this.rotationQuaternion) {
  33342. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33343. }
  33344. else if (this.rotation) {
  33345. serializationObject.rotation = this.rotation.asArray();
  33346. }
  33347. serializationObject.scaling = this.scaling.asArray();
  33348. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33349. serializationObject.isEnabled = this.isEnabled(false);
  33350. serializationObject.isVisible = this.isVisible;
  33351. serializationObject.infiniteDistance = this.infiniteDistance;
  33352. serializationObject.pickable = this.isPickable;
  33353. serializationObject.receiveShadows = this.receiveShadows;
  33354. serializationObject.billboardMode = this.billboardMode;
  33355. serializationObject.visibility = this.visibility;
  33356. serializationObject.checkCollisions = this.checkCollisions;
  33357. serializationObject.isBlocker = this.isBlocker;
  33358. // Parent
  33359. if (this.parent) {
  33360. serializationObject.parentId = this.parent.id;
  33361. }
  33362. // Geometry
  33363. serializationObject.isUnIndexed = this.isUnIndexed;
  33364. var geometry = this._geometry;
  33365. if (geometry) {
  33366. var geometryId = geometry.id;
  33367. serializationObject.geometryId = geometryId;
  33368. // SubMeshes
  33369. serializationObject.subMeshes = [];
  33370. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33371. var subMesh = this.subMeshes[subIndex];
  33372. serializationObject.subMeshes.push({
  33373. materialIndex: subMesh.materialIndex,
  33374. verticesStart: subMesh.verticesStart,
  33375. verticesCount: subMesh.verticesCount,
  33376. indexStart: subMesh.indexStart,
  33377. indexCount: subMesh.indexCount
  33378. });
  33379. }
  33380. }
  33381. // Material
  33382. if (this.material) {
  33383. serializationObject.materialId = this.material.id;
  33384. }
  33385. else {
  33386. this.material = null;
  33387. }
  33388. // Morph targets
  33389. if (this.morphTargetManager) {
  33390. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33391. }
  33392. // Skeleton
  33393. if (this.skeleton) {
  33394. serializationObject.skeletonId = this.skeleton.id;
  33395. }
  33396. // Physics
  33397. //TODO implement correct serialization for physics impostors.
  33398. var impostor = this.getPhysicsImpostor();
  33399. if (impostor) {
  33400. serializationObject.physicsMass = impostor.getParam("mass");
  33401. serializationObject.physicsFriction = impostor.getParam("friction");
  33402. serializationObject.physicsRestitution = impostor.getParam("mass");
  33403. serializationObject.physicsImpostor = impostor.type;
  33404. }
  33405. // Metadata
  33406. if (this.metadata) {
  33407. serializationObject.metadata = this.metadata;
  33408. }
  33409. // Instances
  33410. serializationObject.instances = [];
  33411. for (var index = 0; index < this.instances.length; index++) {
  33412. var instance = this.instances[index];
  33413. var serializationInstance = {
  33414. name: instance.name,
  33415. id: instance.id,
  33416. position: instance.position.asArray(),
  33417. scaling: instance.scaling.asArray()
  33418. };
  33419. if (instance.rotationQuaternion) {
  33420. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33421. }
  33422. else if (instance.rotation) {
  33423. serializationInstance.rotation = instance.rotation.asArray();
  33424. }
  33425. serializationObject.instances.push(serializationInstance);
  33426. // Animations
  33427. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33428. serializationInstance.ranges = instance.serializeAnimationRanges();
  33429. }
  33430. //
  33431. // Animations
  33432. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33433. serializationObject.ranges = this.serializeAnimationRanges();
  33434. // Layer mask
  33435. serializationObject.layerMask = this.layerMask;
  33436. // Alpha
  33437. serializationObject.alphaIndex = this.alphaIndex;
  33438. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33439. // Overlay
  33440. serializationObject.overlayAlpha = this.overlayAlpha;
  33441. serializationObject.overlayColor = this.overlayColor.asArray();
  33442. serializationObject.renderOverlay = this.renderOverlay;
  33443. // Fog
  33444. serializationObject.applyFog = this.applyFog;
  33445. // Action Manager
  33446. if (this.actionManager) {
  33447. serializationObject.actions = this.actionManager.serialize(this.name);
  33448. }
  33449. };
  33450. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33451. if (!this.geometry) {
  33452. return;
  33453. }
  33454. this._markSubMeshesAsAttributesDirty();
  33455. var morphTargetManager = this._morphTargetManager;
  33456. if (morphTargetManager && morphTargetManager.vertexCount) {
  33457. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33458. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33459. this.morphTargetManager = null;
  33460. return;
  33461. }
  33462. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33463. var morphTarget = morphTargetManager.getActiveTarget(index);
  33464. var positions = morphTarget.getPositions();
  33465. if (!positions) {
  33466. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33467. return;
  33468. }
  33469. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33470. var normals = morphTarget.getNormals();
  33471. if (normals) {
  33472. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33473. }
  33474. var tangents = morphTarget.getTangents();
  33475. if (tangents) {
  33476. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33477. }
  33478. }
  33479. }
  33480. else {
  33481. var index = 0;
  33482. // Positions
  33483. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33484. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33485. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33486. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33487. }
  33488. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33489. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33490. }
  33491. index++;
  33492. }
  33493. }
  33494. };
  33495. // Statics
  33496. /**
  33497. * Returns a new Mesh object parsed from the source provided.
  33498. * The parameter `parsedMesh` is the source.
  33499. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33500. */
  33501. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33502. var mesh;
  33503. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33504. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33505. }
  33506. else {
  33507. mesh = new Mesh(parsedMesh.name, scene);
  33508. }
  33509. mesh.id = parsedMesh.id;
  33510. if (BABYLON.Tags) {
  33511. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33512. }
  33513. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33514. if (parsedMesh.metadata !== undefined) {
  33515. mesh.metadata = parsedMesh.metadata;
  33516. }
  33517. if (parsedMesh.rotationQuaternion) {
  33518. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33519. }
  33520. else if (parsedMesh.rotation) {
  33521. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33522. }
  33523. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33524. if (parsedMesh.localMatrix) {
  33525. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33526. }
  33527. else if (parsedMesh.pivotMatrix) {
  33528. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33529. }
  33530. mesh.setEnabled(parsedMesh.isEnabled);
  33531. mesh.isVisible = parsedMesh.isVisible;
  33532. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33533. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33534. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33535. if (parsedMesh.applyFog !== undefined) {
  33536. mesh.applyFog = parsedMesh.applyFog;
  33537. }
  33538. if (parsedMesh.pickable !== undefined) {
  33539. mesh.isPickable = parsedMesh.pickable;
  33540. }
  33541. if (parsedMesh.alphaIndex !== undefined) {
  33542. mesh.alphaIndex = parsedMesh.alphaIndex;
  33543. }
  33544. mesh.receiveShadows = parsedMesh.receiveShadows;
  33545. mesh.billboardMode = parsedMesh.billboardMode;
  33546. if (parsedMesh.visibility !== undefined) {
  33547. mesh.visibility = parsedMesh.visibility;
  33548. }
  33549. mesh.checkCollisions = parsedMesh.checkCollisions;
  33550. if (parsedMesh.isBlocker !== undefined) {
  33551. mesh.isBlocker = parsedMesh.isBlocker;
  33552. }
  33553. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33554. // freezeWorldMatrix
  33555. if (parsedMesh.freezeWorldMatrix) {
  33556. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33557. }
  33558. // Parent
  33559. if (parsedMesh.parentId) {
  33560. mesh._waitingParentId = parsedMesh.parentId;
  33561. }
  33562. // Actions
  33563. if (parsedMesh.actions !== undefined) {
  33564. mesh._waitingActions = parsedMesh.actions;
  33565. }
  33566. // Overlay
  33567. if (parsedMesh.overlayAlpha !== undefined) {
  33568. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33569. }
  33570. if (parsedMesh.overlayColor !== undefined) {
  33571. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33572. }
  33573. if (parsedMesh.renderOverlay !== undefined) {
  33574. mesh.renderOverlay = parsedMesh.renderOverlay;
  33575. }
  33576. // Geometry
  33577. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33578. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33579. if (parsedMesh.delayLoadingFile) {
  33580. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33581. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33582. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33583. if (parsedMesh._binaryInfo) {
  33584. mesh._binaryInfo = parsedMesh._binaryInfo;
  33585. }
  33586. mesh._delayInfo = [];
  33587. if (parsedMesh.hasUVs) {
  33588. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33589. }
  33590. if (parsedMesh.hasUVs2) {
  33591. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33592. }
  33593. if (parsedMesh.hasUVs3) {
  33594. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33595. }
  33596. if (parsedMesh.hasUVs4) {
  33597. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33598. }
  33599. if (parsedMesh.hasUVs5) {
  33600. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33601. }
  33602. if (parsedMesh.hasUVs6) {
  33603. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33604. }
  33605. if (parsedMesh.hasColors) {
  33606. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33607. }
  33608. if (parsedMesh.hasMatricesIndices) {
  33609. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33610. }
  33611. if (parsedMesh.hasMatricesWeights) {
  33612. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33613. }
  33614. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33615. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33616. mesh._checkDelayState();
  33617. }
  33618. }
  33619. else {
  33620. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33621. }
  33622. // Material
  33623. if (parsedMesh.materialId) {
  33624. mesh.setMaterialByID(parsedMesh.materialId);
  33625. }
  33626. else {
  33627. mesh.material = null;
  33628. }
  33629. // Morph targets
  33630. if (parsedMesh.morphTargetManagerId > -1) {
  33631. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33632. }
  33633. // Skeleton
  33634. if (parsedMesh.skeletonId > -1) {
  33635. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33636. if (parsedMesh.numBoneInfluencers) {
  33637. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33638. }
  33639. }
  33640. // Animations
  33641. if (parsedMesh.animations) {
  33642. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33643. var parsedAnimation = parsedMesh.animations[animationIndex];
  33644. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33645. }
  33646. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33647. }
  33648. if (parsedMesh.autoAnimate) {
  33649. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33650. }
  33651. // Layer Mask
  33652. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33653. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33654. }
  33655. else {
  33656. mesh.layerMask = 0x0FFFFFFF;
  33657. }
  33658. // Physics
  33659. if (parsedMesh.physicsImpostor) {
  33660. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33661. mass: parsedMesh.physicsMass,
  33662. friction: parsedMesh.physicsFriction,
  33663. restitution: parsedMesh.physicsRestitution
  33664. }, scene);
  33665. }
  33666. // Instances
  33667. if (parsedMesh.instances) {
  33668. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33669. var parsedInstance = parsedMesh.instances[index];
  33670. var instance = mesh.createInstance(parsedInstance.name);
  33671. if (parsedInstance.id) {
  33672. instance.id = parsedInstance.id;
  33673. }
  33674. if (BABYLON.Tags) {
  33675. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33676. }
  33677. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33678. if (parsedInstance.parentId) {
  33679. instance._waitingParentId = parsedInstance.parentId;
  33680. }
  33681. if (parsedInstance.rotationQuaternion) {
  33682. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33683. }
  33684. else if (parsedInstance.rotation) {
  33685. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33686. }
  33687. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33688. instance.checkCollisions = mesh.checkCollisions;
  33689. if (parsedMesh.animations) {
  33690. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33691. parsedAnimation = parsedMesh.animations[animationIndex];
  33692. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33693. }
  33694. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33695. if (parsedMesh.autoAnimate) {
  33696. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33697. }
  33698. }
  33699. }
  33700. }
  33701. return mesh;
  33702. };
  33703. /**
  33704. * Creates a ribbon mesh.
  33705. * Please consider using the same method from the MeshBuilder class instead.
  33706. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33707. *
  33708. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33709. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33710. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33711. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33712. * 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.
  33713. * 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.
  33714. * 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
  33715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33716. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33717. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33718. */
  33719. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33720. if (closeArray === void 0) { closeArray = false; }
  33721. if (updatable === void 0) { updatable = false; }
  33722. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33723. pathArray: pathArray,
  33724. closeArray: closeArray,
  33725. closePath: closePath,
  33726. offset: offset,
  33727. updatable: updatable,
  33728. sideOrientation: sideOrientation,
  33729. instance: instance
  33730. }, scene);
  33731. };
  33732. /**
  33733. * Creates a plane polygonal mesh. By default, this is a disc.
  33734. * Please consider using the same method from the MeshBuilder class instead.
  33735. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33736. * 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.
  33737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33738. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33740. */
  33741. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33742. if (scene === void 0) { scene = null; }
  33743. var options = {
  33744. radius: radius,
  33745. tessellation: tessellation,
  33746. sideOrientation: sideOrientation,
  33747. updatable: updatable
  33748. };
  33749. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33750. };
  33751. /**
  33752. * Creates a box mesh.
  33753. * Please consider using the same method from the MeshBuilder class instead.
  33754. * The parameter `size` sets the size (float) of each box side (default 1).
  33755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33756. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33758. */
  33759. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33760. if (scene === void 0) { scene = null; }
  33761. var options = {
  33762. size: size,
  33763. sideOrientation: sideOrientation,
  33764. updatable: updatable
  33765. };
  33766. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33767. };
  33768. /**
  33769. * Creates a sphere mesh.
  33770. * Please consider using the same method from the MeshBuilder class instead.
  33771. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33772. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33774. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33776. */
  33777. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33778. var options = {
  33779. segments: segments,
  33780. diameterX: diameter,
  33781. diameterY: diameter,
  33782. diameterZ: diameter,
  33783. sideOrientation: sideOrientation,
  33784. updatable: updatable
  33785. };
  33786. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33787. };
  33788. /**
  33789. * Creates a cylinder or a cone mesh.
  33790. * Please consider using the same method from the MeshBuilder class instead.
  33791. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33792. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33793. * 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.
  33794. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33795. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33797. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33799. */
  33800. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33801. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33802. if (scene !== undefined) {
  33803. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33804. updatable = scene;
  33805. }
  33806. scene = subdivisions;
  33807. subdivisions = 1;
  33808. }
  33809. var options = {
  33810. height: height,
  33811. diameterTop: diameterTop,
  33812. diameterBottom: diameterBottom,
  33813. tessellation: tessellation,
  33814. subdivisions: subdivisions,
  33815. sideOrientation: sideOrientation,
  33816. updatable: updatable
  33817. };
  33818. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33819. };
  33820. // Torus (Code from SharpDX.org)
  33821. /**
  33822. * Creates a torus mesh.
  33823. * Please consider using the same method from the MeshBuilder class instead.
  33824. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33825. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33826. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33828. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33830. */
  33831. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33832. var options = {
  33833. diameter: diameter,
  33834. thickness: thickness,
  33835. tessellation: tessellation,
  33836. sideOrientation: sideOrientation,
  33837. updatable: updatable
  33838. };
  33839. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33840. };
  33841. /**
  33842. * Creates a torus knot mesh.
  33843. * Please consider using the same method from the MeshBuilder class instead.
  33844. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33845. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33846. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33847. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33849. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33851. */
  33852. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33853. var options = {
  33854. radius: radius,
  33855. tube: tube,
  33856. radialSegments: radialSegments,
  33857. tubularSegments: tubularSegments,
  33858. p: p,
  33859. q: q,
  33860. sideOrientation: sideOrientation,
  33861. updatable: updatable
  33862. };
  33863. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33864. };
  33865. /**
  33866. * Creates a line mesh.
  33867. * Please consider using the same method from the MeshBuilder class instead.
  33868. * 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.
  33869. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33870. * The parameter `points` is an array successive Vector3.
  33871. * 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
  33872. * When updating an instance, remember that only point positions can change, not the number of points.
  33873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33874. */
  33875. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33876. if (scene === void 0) { scene = null; }
  33877. if (updatable === void 0) { updatable = false; }
  33878. if (instance === void 0) { instance = null; }
  33879. var options = {
  33880. points: points,
  33881. updatable: updatable,
  33882. instance: instance
  33883. };
  33884. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33885. };
  33886. /**
  33887. * Creates a dashed line mesh.
  33888. * Please consider using the same method from the MeshBuilder class instead.
  33889. * 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.
  33890. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33891. * The parameter `points` is an array successive Vector3.
  33892. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33893. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33894. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33895. * 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
  33896. * When updating an instance, remember that only point positions can change, not the number of points.
  33897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33898. */
  33899. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33900. if (scene === void 0) { scene = null; }
  33901. var options = {
  33902. points: points,
  33903. dashSize: dashSize,
  33904. gapSize: gapSize,
  33905. dashNb: dashNb,
  33906. updatable: updatable,
  33907. instance: instance
  33908. };
  33909. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33910. };
  33911. /**
  33912. * Creates a polygon mesh.
  33913. * Please consider using the same method from the MeshBuilder class instead.
  33914. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33915. * 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.
  33916. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33918. * Remember you can only change the shape positions, not their number when updating a polygon.
  33919. */
  33920. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33921. var options = {
  33922. shape: shape,
  33923. holes: holes,
  33924. updatable: updatable,
  33925. sideOrientation: sideOrientation
  33926. };
  33927. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33928. };
  33929. /**
  33930. * Creates an extruded polygon mesh, with depth in the Y direction.
  33931. * Please consider using the same method from the MeshBuilder class instead.
  33932. */
  33933. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33934. var options = {
  33935. shape: shape,
  33936. holes: holes,
  33937. depth: depth,
  33938. updatable: updatable,
  33939. sideOrientation: sideOrientation
  33940. };
  33941. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33942. };
  33943. /**
  33944. * Creates an extruded shape mesh.
  33945. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33946. * Please consider using the same method from the MeshBuilder class instead.
  33947. *
  33948. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33949. * 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
  33950. * extruded along the Z axis.
  33951. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33952. * 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.
  33953. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33954. * 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
  33955. * 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
  33956. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33958. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33960. */
  33961. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33962. if (scene === void 0) { scene = null; }
  33963. var options = {
  33964. shape: shape,
  33965. path: path,
  33966. scale: scale,
  33967. rotation: rotation,
  33968. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33969. sideOrientation: sideOrientation,
  33970. instance: instance,
  33971. updatable: updatable
  33972. };
  33973. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33974. };
  33975. /**
  33976. * Creates an custom extruded shape mesh.
  33977. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33978. * Please consider using the same method from the MeshBuilder class instead.
  33979. *
  33980. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33981. * 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
  33982. * extruded along the Z axis.
  33983. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33984. * 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
  33985. * and the distance of this point from the begining of the path :
  33986. * ```javascript
  33987. * var rotationFunction = function(i, distance) {
  33988. * // do things
  33989. * return rotationValue; }
  33990. * ```
  33991. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33992. * 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
  33993. * and the distance of this point from the begining of the path :
  33994. * ```javascript
  33995. * var scaleFunction = function(i, distance) {
  33996. * // do things
  33997. * return scaleValue;}
  33998. * ```
  33999. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34000. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34001. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34002. * 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
  34003. * 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
  34004. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34006. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34008. */
  34009. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34010. var options = {
  34011. shape: shape,
  34012. path: path,
  34013. scaleFunction: scaleFunction,
  34014. rotationFunction: rotationFunction,
  34015. ribbonCloseArray: ribbonCloseArray,
  34016. ribbonClosePath: ribbonClosePath,
  34017. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34018. sideOrientation: sideOrientation,
  34019. instance: instance,
  34020. updatable: updatable
  34021. };
  34022. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34023. };
  34024. /**
  34025. * Creates lathe mesh.
  34026. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34027. * Please consider using the same method from the MeshBuilder class instead.
  34028. * 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
  34029. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34030. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34031. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34033. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34035. */
  34036. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34037. var options = {
  34038. shape: shape,
  34039. radius: radius,
  34040. tessellation: tessellation,
  34041. sideOrientation: sideOrientation,
  34042. updatable: updatable
  34043. };
  34044. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34045. };
  34046. /**
  34047. * Creates a plane mesh.
  34048. * Please consider using the same method from the MeshBuilder class instead.
  34049. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34051. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34053. */
  34054. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34055. var options = {
  34056. size: size,
  34057. width: size,
  34058. height: size,
  34059. sideOrientation: sideOrientation,
  34060. updatable: updatable
  34061. };
  34062. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34063. };
  34064. /**
  34065. * Creates a ground mesh.
  34066. * Please consider using the same method from the MeshBuilder class instead.
  34067. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34068. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34070. */
  34071. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34072. var options = {
  34073. width: width,
  34074. height: height,
  34075. subdivisions: subdivisions,
  34076. updatable: updatable
  34077. };
  34078. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34079. };
  34080. /**
  34081. * Creates a tiled ground mesh.
  34082. * Please consider using the same method from the MeshBuilder class instead.
  34083. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34084. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34085. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34086. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34087. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34088. * numbers of subdivisions on the ground width and height of each tile.
  34089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34090. */
  34091. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34092. var options = {
  34093. xmin: xmin,
  34094. zmin: zmin,
  34095. xmax: xmax,
  34096. zmax: zmax,
  34097. subdivisions: subdivisions,
  34098. precision: precision,
  34099. updatable: updatable
  34100. };
  34101. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34102. };
  34103. /**
  34104. * Creates a ground mesh from a height map.
  34105. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34106. * Please consider using the same method from the MeshBuilder class instead.
  34107. * The parameter `url` sets the URL of the height map image resource.
  34108. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34109. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34110. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34111. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34112. * 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).
  34113. * This function is passed the newly built mesh :
  34114. * ```javascript
  34115. * function(mesh) { // do things
  34116. * return; }
  34117. * ```
  34118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34119. */
  34120. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34121. var options = {
  34122. width: width,
  34123. height: height,
  34124. subdivisions: subdivisions,
  34125. minHeight: minHeight,
  34126. maxHeight: maxHeight,
  34127. updatable: updatable,
  34128. onReady: onReady
  34129. };
  34130. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34131. };
  34132. /**
  34133. * Creates a tube mesh.
  34134. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34135. * Please consider using the same method from the MeshBuilder class instead.
  34136. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34137. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34138. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34139. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34140. * 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.
  34141. * It must return a radius value (positive float) :
  34142. * ```javascript
  34143. * var radiusFunction = function(i, distance) {
  34144. * // do things
  34145. * return radius; }
  34146. * ```
  34147. * 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
  34148. * 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
  34149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34150. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34152. */
  34153. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34154. var options = {
  34155. path: path,
  34156. radius: radius,
  34157. tessellation: tessellation,
  34158. radiusFunction: radiusFunction,
  34159. arc: 1,
  34160. cap: cap,
  34161. updatable: updatable,
  34162. sideOrientation: sideOrientation,
  34163. instance: instance
  34164. };
  34165. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34166. };
  34167. /**
  34168. * Creates a polyhedron mesh.
  34169. * Please consider using the same method from the MeshBuilder class instead.
  34170. * 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
  34171. * to choose the wanted type.
  34172. * The parameter `size` (positive float, default 1) sets the polygon size.
  34173. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34174. * 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`.
  34175. * 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
  34176. * 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)`).
  34177. * 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
  34178. * 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.
  34179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34180. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34182. */
  34183. Mesh.CreatePolyhedron = function (name, options, scene) {
  34184. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34185. };
  34186. /**
  34187. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34188. * Please consider using the same method from the MeshBuilder class instead.
  34189. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34190. * 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`).
  34191. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34192. * 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.
  34193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34194. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34196. */
  34197. Mesh.CreateIcoSphere = function (name, options, scene) {
  34198. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34199. };
  34200. /**
  34201. * Creates a decal mesh.
  34202. * Please consider using the same method from the MeshBuilder class instead.
  34203. * 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.
  34204. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34205. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34206. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34207. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34208. */
  34209. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34210. var options = {
  34211. position: position,
  34212. normal: normal,
  34213. size: size,
  34214. angle: angle
  34215. };
  34216. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34217. };
  34218. // Skeletons
  34219. /**
  34220. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34221. */
  34222. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34223. if (!this._sourcePositions) {
  34224. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34225. if (!source) {
  34226. return this._sourcePositions;
  34227. }
  34228. this._sourcePositions = new Float32Array(source);
  34229. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34230. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34231. }
  34232. }
  34233. return this._sourcePositions;
  34234. };
  34235. /**
  34236. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34237. */
  34238. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34239. if (!this._sourceNormals) {
  34240. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34241. if (!source) {
  34242. return this._sourceNormals;
  34243. }
  34244. this._sourceNormals = new Float32Array(source);
  34245. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34246. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34247. }
  34248. }
  34249. return this._sourceNormals;
  34250. };
  34251. /**
  34252. * Updates the vertex buffer by applying transformation from the bones.
  34253. * Returns the Mesh.
  34254. *
  34255. * @param {skeleton} skeleton to apply
  34256. */
  34257. Mesh.prototype.applySkeleton = function (skeleton) {
  34258. if (!this.geometry) {
  34259. return this;
  34260. }
  34261. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34262. return this;
  34263. }
  34264. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34265. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34266. return this;
  34267. }
  34268. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34269. return this;
  34270. }
  34271. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34272. return this;
  34273. }
  34274. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34275. return this;
  34276. }
  34277. if (!this._sourcePositions) {
  34278. var submeshes = this.subMeshes.slice();
  34279. this.setPositionsForCPUSkinning();
  34280. this.subMeshes = submeshes;
  34281. }
  34282. if (!this._sourceNormals) {
  34283. this.setNormalsForCPUSkinning();
  34284. }
  34285. // positionsData checks for not being Float32Array will only pass at most once
  34286. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34287. if (!positionsData) {
  34288. return this;
  34289. }
  34290. if (!(positionsData instanceof Float32Array)) {
  34291. positionsData = new Float32Array(positionsData);
  34292. }
  34293. // normalsData checks for not being Float32Array will only pass at most once
  34294. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34295. if (!normalsData) {
  34296. return this;
  34297. }
  34298. if (!(normalsData instanceof Float32Array)) {
  34299. normalsData = new Float32Array(normalsData);
  34300. }
  34301. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34302. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34303. if (!matricesWeightsData || !matricesIndicesData) {
  34304. return this;
  34305. }
  34306. var needExtras = this.numBoneInfluencers > 4;
  34307. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34308. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34309. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34310. var tempVector3 = BABYLON.Vector3.Zero();
  34311. var finalMatrix = new BABYLON.Matrix();
  34312. var tempMatrix = new BABYLON.Matrix();
  34313. var matWeightIdx = 0;
  34314. var inf;
  34315. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34316. var weight;
  34317. for (inf = 0; inf < 4; inf++) {
  34318. weight = matricesWeightsData[matWeightIdx + inf];
  34319. if (weight > 0) {
  34320. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34321. finalMatrix.addToSelf(tempMatrix);
  34322. }
  34323. else
  34324. break;
  34325. }
  34326. if (needExtras) {
  34327. for (inf = 0; inf < 4; inf++) {
  34328. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34329. if (weight > 0) {
  34330. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34331. finalMatrix.addToSelf(tempMatrix);
  34332. }
  34333. else
  34334. break;
  34335. }
  34336. }
  34337. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34338. tempVector3.toArray(positionsData, index);
  34339. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34340. tempVector3.toArray(normalsData, index);
  34341. finalMatrix.reset();
  34342. }
  34343. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34344. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34345. return this;
  34346. };
  34347. // Tools
  34348. /**
  34349. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34350. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34351. */
  34352. Mesh.MinMax = function (meshes) {
  34353. var minVector = null;
  34354. var maxVector = null;
  34355. meshes.forEach(function (mesh, index, array) {
  34356. var boundingInfo = mesh.getBoundingInfo();
  34357. var boundingBox = boundingInfo.boundingBox;
  34358. if (!minVector || !maxVector) {
  34359. minVector = boundingBox.minimumWorld;
  34360. maxVector = boundingBox.maximumWorld;
  34361. }
  34362. else {
  34363. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34364. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34365. }
  34366. });
  34367. if (!minVector || !maxVector) {
  34368. return {
  34369. min: BABYLON.Vector3.Zero(),
  34370. max: BABYLON.Vector3.Zero()
  34371. };
  34372. }
  34373. return {
  34374. min: minVector,
  34375. max: maxVector
  34376. };
  34377. };
  34378. /**
  34379. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34380. */
  34381. Mesh.Center = function (meshesOrMinMaxVector) {
  34382. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34383. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34384. };
  34385. /**
  34386. * Merge the array of meshes into a single mesh for performance reasons.
  34387. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34388. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34389. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34390. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34391. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34392. */
  34393. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34394. if (disposeSource === void 0) { disposeSource = true; }
  34395. var index;
  34396. if (!allow32BitsIndices) {
  34397. var totalVertices = 0;
  34398. // Counting vertices
  34399. for (index = 0; index < meshes.length; index++) {
  34400. if (meshes[index]) {
  34401. totalVertices += meshes[index].getTotalVertices();
  34402. if (totalVertices > 65536) {
  34403. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34404. return null;
  34405. }
  34406. }
  34407. }
  34408. }
  34409. // Merge
  34410. var vertexData = null;
  34411. var otherVertexData;
  34412. var indiceArray = new Array();
  34413. var source = null;
  34414. for (index = 0; index < meshes.length; index++) {
  34415. if (meshes[index]) {
  34416. meshes[index].computeWorldMatrix(true);
  34417. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34418. otherVertexData.transform(meshes[index].getWorldMatrix());
  34419. if (vertexData) {
  34420. vertexData.merge(otherVertexData);
  34421. }
  34422. else {
  34423. vertexData = otherVertexData;
  34424. source = meshes[index];
  34425. }
  34426. if (subdivideWithSubMeshes) {
  34427. indiceArray.push(meshes[index].getTotalIndices());
  34428. }
  34429. }
  34430. }
  34431. source = source;
  34432. if (!meshSubclass) {
  34433. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34434. }
  34435. vertexData.applyToMesh(meshSubclass);
  34436. // Setting properties
  34437. meshSubclass.material = source.material;
  34438. meshSubclass.checkCollisions = source.checkCollisions;
  34439. // Cleaning
  34440. if (disposeSource) {
  34441. for (index = 0; index < meshes.length; index++) {
  34442. if (meshes[index]) {
  34443. meshes[index].dispose();
  34444. }
  34445. }
  34446. }
  34447. // Subdivide
  34448. if (subdivideWithSubMeshes) {
  34449. //-- removal of global submesh
  34450. meshSubclass.releaseSubMeshes();
  34451. index = 0;
  34452. var offset = 0;
  34453. //-- apply subdivision according to index table
  34454. while (index < indiceArray.length) {
  34455. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34456. offset += indiceArray[index];
  34457. index++;
  34458. }
  34459. }
  34460. return meshSubclass;
  34461. };
  34462. // Consts
  34463. Mesh._FRONTSIDE = 0;
  34464. Mesh._BACKSIDE = 1;
  34465. Mesh._DOUBLESIDE = 2;
  34466. Mesh._DEFAULTSIDE = 0;
  34467. Mesh._NO_CAP = 0;
  34468. Mesh._CAP_START = 1;
  34469. Mesh._CAP_END = 2;
  34470. Mesh._CAP_ALL = 3;
  34471. return Mesh;
  34472. }(BABYLON.AbstractMesh));
  34473. BABYLON.Mesh = Mesh;
  34474. })(BABYLON || (BABYLON = {}));
  34475. //# sourceMappingURL=babylon.mesh.js.map
  34476. var BABYLON;
  34477. (function (BABYLON) {
  34478. var BaseSubMesh = /** @class */ (function () {
  34479. function BaseSubMesh() {
  34480. }
  34481. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34482. get: function () {
  34483. return this._materialEffect;
  34484. },
  34485. enumerable: true,
  34486. configurable: true
  34487. });
  34488. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34489. if (defines === void 0) { defines = null; }
  34490. if (this._materialEffect === effect) {
  34491. if (!effect) {
  34492. this._materialDefines = null;
  34493. }
  34494. return;
  34495. }
  34496. this._materialDefines = defines;
  34497. this._materialEffect = effect;
  34498. };
  34499. return BaseSubMesh;
  34500. }());
  34501. BABYLON.BaseSubMesh = BaseSubMesh;
  34502. var SubMesh = /** @class */ (function (_super) {
  34503. __extends(SubMesh, _super);
  34504. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34505. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34506. var _this = _super.call(this) || this;
  34507. _this.materialIndex = materialIndex;
  34508. _this.verticesStart = verticesStart;
  34509. _this.verticesCount = verticesCount;
  34510. _this.indexStart = indexStart;
  34511. _this.indexCount = indexCount;
  34512. _this._renderId = 0;
  34513. _this._mesh = mesh;
  34514. _this._renderingMesh = renderingMesh || mesh;
  34515. mesh.subMeshes.push(_this);
  34516. _this._trianglePlanes = [];
  34517. _this._id = mesh.subMeshes.length - 1;
  34518. if (createBoundingBox) {
  34519. _this.refreshBoundingInfo();
  34520. mesh.computeWorldMatrix(true);
  34521. }
  34522. return _this;
  34523. }
  34524. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34525. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34526. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34527. };
  34528. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34529. get: function () {
  34530. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34531. },
  34532. enumerable: true,
  34533. configurable: true
  34534. });
  34535. /**
  34536. * Returns the submesh BoudingInfo object.
  34537. */
  34538. SubMesh.prototype.getBoundingInfo = function () {
  34539. if (this.IsGlobal) {
  34540. return this._mesh.getBoundingInfo();
  34541. }
  34542. return this._boundingInfo;
  34543. };
  34544. /**
  34545. * Sets the submesh BoundingInfo.
  34546. * Return the SubMesh.
  34547. */
  34548. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34549. this._boundingInfo = boundingInfo;
  34550. return this;
  34551. };
  34552. /**
  34553. * Returns the mesh of the current submesh.
  34554. */
  34555. SubMesh.prototype.getMesh = function () {
  34556. return this._mesh;
  34557. };
  34558. /**
  34559. * Returns the rendering mesh of the submesh.
  34560. */
  34561. SubMesh.prototype.getRenderingMesh = function () {
  34562. return this._renderingMesh;
  34563. };
  34564. /**
  34565. * Returns the submesh material.
  34566. */
  34567. SubMesh.prototype.getMaterial = function () {
  34568. var rootMaterial = this._renderingMesh.material;
  34569. if (rootMaterial === null || rootMaterial === undefined) {
  34570. return this._mesh.getScene().defaultMaterial;
  34571. }
  34572. else if (rootMaterial.getSubMaterial) {
  34573. var multiMaterial = rootMaterial;
  34574. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34575. if (this._currentMaterial !== effectiveMaterial) {
  34576. this._currentMaterial = effectiveMaterial;
  34577. this._materialDefines = null;
  34578. }
  34579. return effectiveMaterial;
  34580. }
  34581. return rootMaterial;
  34582. };
  34583. // Methods
  34584. /**
  34585. * Sets a new updated BoundingInfo object to the submesh.
  34586. * Returns the SubMesh.
  34587. */
  34588. SubMesh.prototype.refreshBoundingInfo = function () {
  34589. this._lastColliderWorldVertices = null;
  34590. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34591. return this;
  34592. }
  34593. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34594. if (!data) {
  34595. this._boundingInfo = this._mesh.getBoundingInfo();
  34596. return this;
  34597. }
  34598. var indices = this._renderingMesh.getIndices();
  34599. var extend;
  34600. //is this the only submesh?
  34601. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34602. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34603. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34604. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34605. }
  34606. else {
  34607. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34608. }
  34609. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34610. return this;
  34611. };
  34612. SubMesh.prototype._checkCollision = function (collider) {
  34613. var boundingInfo = this.getBoundingInfo();
  34614. return boundingInfo._checkCollision(collider);
  34615. };
  34616. /**
  34617. * Updates the submesh BoundingInfo.
  34618. * Returns the Submesh.
  34619. */
  34620. SubMesh.prototype.updateBoundingInfo = function (world) {
  34621. var boundingInfo = this.getBoundingInfo();
  34622. if (!boundingInfo) {
  34623. this.refreshBoundingInfo();
  34624. boundingInfo = this.getBoundingInfo();
  34625. }
  34626. boundingInfo.update(world);
  34627. return this;
  34628. };
  34629. /**
  34630. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34631. * Boolean returned.
  34632. */
  34633. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34634. var boundingInfo = this.getBoundingInfo();
  34635. if (!boundingInfo) {
  34636. return false;
  34637. }
  34638. return boundingInfo.isInFrustum(frustumPlanes);
  34639. };
  34640. /**
  34641. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34642. * Boolean returned.
  34643. */
  34644. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34645. var boundingInfo = this.getBoundingInfo();
  34646. if (!boundingInfo) {
  34647. return false;
  34648. }
  34649. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34650. };
  34651. /**
  34652. * Renders the submesh.
  34653. * Returns it.
  34654. */
  34655. SubMesh.prototype.render = function (enableAlphaMode) {
  34656. this._renderingMesh.render(this, enableAlphaMode);
  34657. return this;
  34658. };
  34659. /**
  34660. * Returns a new Index Buffer.
  34661. * Type returned : WebGLBuffer.
  34662. */
  34663. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34664. if (!this._linesIndexBuffer) {
  34665. var linesIndices = [];
  34666. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34667. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34668. }
  34669. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34670. this.linesIndexCount = linesIndices.length;
  34671. }
  34672. return this._linesIndexBuffer;
  34673. };
  34674. /**
  34675. * True is the passed Ray intersects the submesh bounding box.
  34676. * Boolean returned.
  34677. */
  34678. SubMesh.prototype.canIntersects = function (ray) {
  34679. var boundingInfo = this.getBoundingInfo();
  34680. if (!boundingInfo) {
  34681. return false;
  34682. }
  34683. return ray.intersectsBox(boundingInfo.boundingBox);
  34684. };
  34685. /**
  34686. * Returns an object IntersectionInfo.
  34687. */
  34688. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34689. var intersectInfo = null;
  34690. var material = this.getMaterial();
  34691. if (!material) {
  34692. return null;
  34693. }
  34694. switch (material.fillMode) {
  34695. case BABYLON.Material.PointListDrawMode:
  34696. case BABYLON.Material.LineListDrawMode:
  34697. case BABYLON.Material.LineLoopDrawMode:
  34698. case BABYLON.Material.LineStripDrawMode:
  34699. case BABYLON.Material.TriangleFanDrawMode:
  34700. case BABYLON.Material.TriangleStripDrawMode:
  34701. return null;
  34702. }
  34703. // LineMesh first as it's also a Mesh...
  34704. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34705. var lineMesh = this._mesh;
  34706. // Line test
  34707. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34708. var p0 = positions[indices[index]];
  34709. var p1 = positions[indices[index + 1]];
  34710. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34711. if (length < 0) {
  34712. continue;
  34713. }
  34714. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34715. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34716. if (fastCheck) {
  34717. break;
  34718. }
  34719. }
  34720. }
  34721. }
  34722. else {
  34723. // Triangles test
  34724. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34725. var p0 = positions[indices[index]];
  34726. var p1 = positions[indices[index + 1]];
  34727. var p2 = positions[indices[index + 2]];
  34728. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34729. if (currentIntersectInfo) {
  34730. if (currentIntersectInfo.distance < 0) {
  34731. continue;
  34732. }
  34733. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34734. intersectInfo = currentIntersectInfo;
  34735. intersectInfo.faceId = index / 3;
  34736. if (fastCheck) {
  34737. break;
  34738. }
  34739. }
  34740. }
  34741. }
  34742. }
  34743. return intersectInfo;
  34744. };
  34745. SubMesh.prototype._rebuild = function () {
  34746. if (this._linesIndexBuffer) {
  34747. this._linesIndexBuffer = null;
  34748. }
  34749. };
  34750. // Clone
  34751. /**
  34752. * Creates a new Submesh from the passed Mesh.
  34753. */
  34754. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34755. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34756. if (!this.IsGlobal) {
  34757. var boundingInfo = this.getBoundingInfo();
  34758. if (!boundingInfo) {
  34759. return result;
  34760. }
  34761. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34762. }
  34763. return result;
  34764. };
  34765. // Dispose
  34766. /**
  34767. * Disposes the Submesh.
  34768. * Returns nothing.
  34769. */
  34770. SubMesh.prototype.dispose = function () {
  34771. if (this._linesIndexBuffer) {
  34772. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34773. this._linesIndexBuffer = null;
  34774. }
  34775. // Remove from mesh
  34776. var index = this._mesh.subMeshes.indexOf(this);
  34777. this._mesh.subMeshes.splice(index, 1);
  34778. };
  34779. // Statics
  34780. /**
  34781. * Creates a new Submesh from the passed parameters :
  34782. * - materialIndex (integer) : the index of the main mesh material.
  34783. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34784. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34785. * - mesh (Mesh) : the main mesh to create the submesh from.
  34786. * - renderingMesh (optional Mesh) : rendering mesh.
  34787. */
  34788. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34789. var minVertexIndex = Number.MAX_VALUE;
  34790. var maxVertexIndex = -Number.MAX_VALUE;
  34791. renderingMesh = (renderingMesh || mesh);
  34792. var indices = renderingMesh.getIndices();
  34793. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34794. var vertexIndex = indices[index];
  34795. if (vertexIndex < minVertexIndex)
  34796. minVertexIndex = vertexIndex;
  34797. if (vertexIndex > maxVertexIndex)
  34798. maxVertexIndex = vertexIndex;
  34799. }
  34800. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34801. };
  34802. return SubMesh;
  34803. }(BaseSubMesh));
  34804. BABYLON.SubMesh = SubMesh;
  34805. })(BABYLON || (BABYLON = {}));
  34806. //# sourceMappingURL=babylon.subMesh.js.map
  34807. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34808. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34809. s = arguments[i];
  34810. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34811. t[p] = s[p];
  34812. }
  34813. return t;
  34814. };
  34815. var BABYLON;
  34816. (function (BABYLON) {
  34817. /**
  34818. * Manages the defines for the Material
  34819. */
  34820. var MaterialDefines = /** @class */ (function () {
  34821. function MaterialDefines() {
  34822. this._isDirty = true;
  34823. /** @hidden */
  34824. this._areLightsDirty = true;
  34825. /** @hidden */
  34826. this._areAttributesDirty = true;
  34827. /** @hidden */
  34828. this._areTexturesDirty = true;
  34829. /** @hidden */
  34830. this._areFresnelDirty = true;
  34831. /** @hidden */
  34832. this._areMiscDirty = true;
  34833. /** @hidden */
  34834. this._areImageProcessingDirty = true;
  34835. /** @hidden */
  34836. this._normals = false;
  34837. /** @hidden */
  34838. this._uvs = false;
  34839. /** @hidden */
  34840. this._needNormals = false;
  34841. /** @hidden */
  34842. this._needUVs = false;
  34843. }
  34844. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34845. /**
  34846. * Specifies if the material needs to be re-calculated
  34847. */
  34848. get: function () {
  34849. return this._isDirty;
  34850. },
  34851. enumerable: true,
  34852. configurable: true
  34853. });
  34854. /**
  34855. * Marks the material to indicate that it has been re-calculated
  34856. */
  34857. MaterialDefines.prototype.markAsProcessed = function () {
  34858. this._isDirty = false;
  34859. this._areAttributesDirty = false;
  34860. this._areTexturesDirty = false;
  34861. this._areFresnelDirty = false;
  34862. this._areLightsDirty = false;
  34863. this._areMiscDirty = false;
  34864. this._areImageProcessingDirty = false;
  34865. };
  34866. /**
  34867. * Marks the material to indicate that it needs to be re-calculated
  34868. */
  34869. MaterialDefines.prototype.markAsUnprocessed = function () {
  34870. this._isDirty = true;
  34871. };
  34872. /**
  34873. * Marks the material to indicate all of its defines need to be re-calculated
  34874. */
  34875. MaterialDefines.prototype.markAllAsDirty = function () {
  34876. this._areTexturesDirty = true;
  34877. this._areAttributesDirty = true;
  34878. this._areLightsDirty = true;
  34879. this._areFresnelDirty = true;
  34880. this._areMiscDirty = true;
  34881. this._areImageProcessingDirty = true;
  34882. this._isDirty = true;
  34883. };
  34884. /**
  34885. * Marks the material to indicate that image processing needs to be re-calculated
  34886. */
  34887. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34888. this._areImageProcessingDirty = true;
  34889. this._isDirty = true;
  34890. };
  34891. /**
  34892. * Marks the material to indicate the lights need to be re-calculated
  34893. */
  34894. MaterialDefines.prototype.markAsLightDirty = function () {
  34895. this._areLightsDirty = true;
  34896. this._isDirty = true;
  34897. };
  34898. /**
  34899. * Marks the attribute state as changed
  34900. */
  34901. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34902. this._areAttributesDirty = true;
  34903. this._isDirty = true;
  34904. };
  34905. /**
  34906. * Marks the texture state as changed
  34907. */
  34908. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34909. this._areTexturesDirty = true;
  34910. this._isDirty = true;
  34911. };
  34912. /**
  34913. * Marks the fresnel state as changed
  34914. */
  34915. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34916. this._areFresnelDirty = true;
  34917. this._isDirty = true;
  34918. };
  34919. /**
  34920. * Marks the misc state as changed
  34921. */
  34922. MaterialDefines.prototype.markAsMiscDirty = function () {
  34923. this._areMiscDirty = true;
  34924. this._isDirty = true;
  34925. };
  34926. /**
  34927. * Rebuilds the material defines
  34928. */
  34929. MaterialDefines.prototype.rebuild = function () {
  34930. if (this._keys) {
  34931. delete this._keys;
  34932. }
  34933. this._keys = [];
  34934. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34935. var key = _a[_i];
  34936. if (key[0] === "_") {
  34937. continue;
  34938. }
  34939. this._keys.push(key);
  34940. }
  34941. };
  34942. /**
  34943. * Specifies if two material defines are equal
  34944. * @param other - A material define instance to compare to
  34945. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34946. */
  34947. MaterialDefines.prototype.isEqual = function (other) {
  34948. if (this._keys.length !== other._keys.length) {
  34949. return false;
  34950. }
  34951. for (var index = 0; index < this._keys.length; index++) {
  34952. var prop = this._keys[index];
  34953. if (this[prop] !== other[prop]) {
  34954. return false;
  34955. }
  34956. }
  34957. return true;
  34958. };
  34959. /**
  34960. * Clones this instance's defines to another instance
  34961. * @param other - material defines to clone values to
  34962. */
  34963. MaterialDefines.prototype.cloneTo = function (other) {
  34964. if (this._keys.length !== other._keys.length) {
  34965. other._keys = this._keys.slice(0);
  34966. }
  34967. for (var index = 0; index < this._keys.length; index++) {
  34968. var prop = this._keys[index];
  34969. other[prop] = this[prop];
  34970. }
  34971. };
  34972. /**
  34973. * Resets the material define values
  34974. */
  34975. MaterialDefines.prototype.reset = function () {
  34976. for (var index = 0; index < this._keys.length; index++) {
  34977. var prop = this._keys[index];
  34978. var type = typeof this[prop];
  34979. switch (type) {
  34980. case "number":
  34981. this[prop] = 0;
  34982. break;
  34983. case "string":
  34984. this[prop] = "";
  34985. break;
  34986. default:
  34987. this[prop] = false;
  34988. break;
  34989. }
  34990. }
  34991. };
  34992. /**
  34993. * Converts the material define values to a string
  34994. * @returns - String of material define information
  34995. */
  34996. MaterialDefines.prototype.toString = function () {
  34997. var result = "";
  34998. for (var index = 0; index < this._keys.length; index++) {
  34999. var prop = this._keys[index];
  35000. var value = this[prop];
  35001. var type = typeof value;
  35002. switch (type) {
  35003. case "number":
  35004. case "string":
  35005. result += "#define " + prop + " " + value + "\n";
  35006. break;
  35007. default:
  35008. if (value) {
  35009. result += "#define " + prop + "\n";
  35010. }
  35011. break;
  35012. }
  35013. }
  35014. return result;
  35015. };
  35016. return MaterialDefines;
  35017. }());
  35018. BABYLON.MaterialDefines = MaterialDefines;
  35019. /**
  35020. * Base class for the main features of a material in Babylon.js
  35021. */
  35022. var Material = /** @class */ (function () {
  35023. /**
  35024. * Creates a material instance
  35025. * @param name defines the name of the material
  35026. * @param scene defines the scene to reference
  35027. * @param doNotAdd specifies if the material should be added to the scene
  35028. */
  35029. function Material(name, scene, doNotAdd) {
  35030. /**
  35031. * Specifies if the ready state should be checked on each call
  35032. */
  35033. this.checkReadyOnEveryCall = false;
  35034. /**
  35035. * Specifies if the ready state should be checked once
  35036. */
  35037. this.checkReadyOnlyOnce = false;
  35038. /**
  35039. * The state of the material
  35040. */
  35041. this.state = "";
  35042. /**
  35043. * The alpha value of the material
  35044. */
  35045. this._alpha = 1.0;
  35046. /**
  35047. * Specifies if back face culling is enabled
  35048. */
  35049. this._backFaceCulling = true;
  35050. /**
  35051. * Specifies if the material should be serialized
  35052. */
  35053. this.doNotSerialize = false;
  35054. /**
  35055. * Specifies if the effect should be stored on sub meshes
  35056. */
  35057. this.storeEffectOnSubMeshes = false;
  35058. /**
  35059. * An event triggered when the material is disposed
  35060. */
  35061. this.onDisposeObservable = new BABYLON.Observable();
  35062. /**
  35063. * An event triggered when the material is bound
  35064. */
  35065. this.onBindObservable = new BABYLON.Observable();
  35066. /**
  35067. * An event triggered when the material is unbound
  35068. */
  35069. this.onUnBindObservable = new BABYLON.Observable();
  35070. /**
  35071. * Stores the value of the alpha mode
  35072. */
  35073. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35074. /**
  35075. * Stores the state of the need depth pre-pass value
  35076. */
  35077. this._needDepthPrePass = false;
  35078. /**
  35079. * Specifies if depth writing should be disabled
  35080. */
  35081. this.disableDepthWrite = false;
  35082. /**
  35083. * Specifies if depth writing should be forced
  35084. */
  35085. this.forceDepthWrite = false;
  35086. /**
  35087. * Specifies if there should be a separate pass for culling
  35088. */
  35089. this.separateCullingPass = false;
  35090. /**
  35091. * Stores the state specifing if fog should be enabled
  35092. */
  35093. this._fogEnabled = true;
  35094. /**
  35095. * Stores the size of points
  35096. */
  35097. this.pointSize = 1.0;
  35098. /**
  35099. * Stores the z offset value
  35100. */
  35101. this.zOffset = 0;
  35102. /**
  35103. * Specifies if the material was previously ready
  35104. */
  35105. this._wasPreviouslyReady = false;
  35106. /**
  35107. * Stores the fill mode state
  35108. */
  35109. this._fillMode = Material.TriangleFillMode;
  35110. this.name = name;
  35111. this.id = name || BABYLON.Tools.RandomId();
  35112. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35113. this.uniqueId = this._scene.getUniqueId();
  35114. if (this._scene.useRightHandedSystem) {
  35115. this.sideOrientation = Material.ClockWiseSideOrientation;
  35116. }
  35117. else {
  35118. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35119. }
  35120. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35121. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35122. if (!doNotAdd) {
  35123. this._scene.materials.push(this);
  35124. }
  35125. }
  35126. Object.defineProperty(Material, "TriangleFillMode", {
  35127. /**
  35128. * Returns the triangle fill mode
  35129. */
  35130. get: function () {
  35131. return Material._TriangleFillMode;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material, "WireFrameFillMode", {
  35137. /**
  35138. * Returns the wireframe mode
  35139. */
  35140. get: function () {
  35141. return Material._WireFrameFillMode;
  35142. },
  35143. enumerable: true,
  35144. configurable: true
  35145. });
  35146. Object.defineProperty(Material, "PointFillMode", {
  35147. /**
  35148. * Returns the point fill mode
  35149. */
  35150. get: function () {
  35151. return Material._PointFillMode;
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(Material, "PointListDrawMode", {
  35157. /**
  35158. * Returns the point list draw mode
  35159. */
  35160. get: function () {
  35161. return Material._PointListDrawMode;
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. Object.defineProperty(Material, "LineListDrawMode", {
  35167. /**
  35168. * Returns the line list draw mode
  35169. */
  35170. get: function () {
  35171. return Material._LineListDrawMode;
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(Material, "LineLoopDrawMode", {
  35177. /**
  35178. * Returns the line loop draw mode
  35179. */
  35180. get: function () {
  35181. return Material._LineLoopDrawMode;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. Object.defineProperty(Material, "LineStripDrawMode", {
  35187. /**
  35188. * Returns the line strip draw mode
  35189. */
  35190. get: function () {
  35191. return Material._LineStripDrawMode;
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35197. /**
  35198. * Returns the triangle strip draw mode
  35199. */
  35200. get: function () {
  35201. return Material._TriangleStripDrawMode;
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35207. /**
  35208. * Returns the triangle fan draw mode
  35209. */
  35210. get: function () {
  35211. return Material._TriangleFanDrawMode;
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35217. /**
  35218. * Returns the clock-wise side orientation
  35219. */
  35220. get: function () {
  35221. return Material._ClockWiseSideOrientation;
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35227. /**
  35228. * Returns the counter clock-wise side orientation
  35229. */
  35230. get: function () {
  35231. return Material._CounterClockWiseSideOrientation;
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(Material, "TextureDirtyFlag", {
  35237. /**
  35238. * Returns the dirty texture flag value
  35239. */
  35240. get: function () {
  35241. return Material._TextureDirtyFlag;
  35242. },
  35243. enumerable: true,
  35244. configurable: true
  35245. });
  35246. Object.defineProperty(Material, "LightDirtyFlag", {
  35247. /**
  35248. * Returns the dirty light flag value
  35249. */
  35250. get: function () {
  35251. return Material._LightDirtyFlag;
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35257. /**
  35258. * Returns the dirty fresnel flag value
  35259. */
  35260. get: function () {
  35261. return Material._FresnelDirtyFlag;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35267. /**
  35268. * Returns the dirty attributes flag value
  35269. */
  35270. get: function () {
  35271. return Material._AttributesDirtyFlag;
  35272. },
  35273. enumerable: true,
  35274. configurable: true
  35275. });
  35276. Object.defineProperty(Material, "MiscDirtyFlag", {
  35277. /**
  35278. * Returns the dirty misc flag value
  35279. */
  35280. get: function () {
  35281. return Material._MiscDirtyFlag;
  35282. },
  35283. enumerable: true,
  35284. configurable: true
  35285. });
  35286. Object.defineProperty(Material.prototype, "alpha", {
  35287. /**
  35288. * Gets the alpha value of the material
  35289. */
  35290. get: function () {
  35291. return this._alpha;
  35292. },
  35293. /**
  35294. * Sets the alpha value of the material
  35295. */
  35296. set: function (value) {
  35297. if (this._alpha === value) {
  35298. return;
  35299. }
  35300. this._alpha = value;
  35301. this.markAsDirty(Material.MiscDirtyFlag);
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35307. /**
  35308. * Gets the back-face culling state
  35309. */
  35310. get: function () {
  35311. return this._backFaceCulling;
  35312. },
  35313. /**
  35314. * Sets the back-face culling state
  35315. */
  35316. set: function (value) {
  35317. if (this._backFaceCulling === value) {
  35318. return;
  35319. }
  35320. this._backFaceCulling = value;
  35321. this.markAsDirty(Material.TextureDirtyFlag);
  35322. },
  35323. enumerable: true,
  35324. configurable: true
  35325. });
  35326. Object.defineProperty(Material.prototype, "onDispose", {
  35327. /**
  35328. * Called during a dispose event
  35329. */
  35330. set: function (callback) {
  35331. if (this._onDisposeObserver) {
  35332. this.onDisposeObservable.remove(this._onDisposeObserver);
  35333. }
  35334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. Object.defineProperty(Material.prototype, "onBind", {
  35340. /**
  35341. * Called during a bind event
  35342. */
  35343. set: function (callback) {
  35344. if (this._onBindObserver) {
  35345. this.onBindObservable.remove(this._onBindObserver);
  35346. }
  35347. this._onBindObserver = this.onBindObservable.add(callback);
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. Object.defineProperty(Material.prototype, "alphaMode", {
  35353. /**
  35354. * Gets the value of the alpha mode
  35355. */
  35356. get: function () {
  35357. return this._alphaMode;
  35358. },
  35359. /**
  35360. * Sets the value of the alpha mode.
  35361. *
  35362. * | Value | Type | Description |
  35363. * | --- | --- | --- |
  35364. * | 0 | ALPHA_DISABLE | |
  35365. * | 1 | ALPHA_ADD | |
  35366. * | 2 | ALPHA_COMBINE | |
  35367. * | 3 | ALPHA_SUBTRACT | |
  35368. * | 4 | ALPHA_MULTIPLY | |
  35369. * | 5 | ALPHA_MAXIMIZED | |
  35370. * | 6 | ALPHA_ONEONE | |
  35371. * | 7 | ALPHA_PREMULTIPLIED | |
  35372. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35373. * | 9 | ALPHA_INTERPOLATE | |
  35374. * | 10 | ALPHA_SCREENMODE | |
  35375. *
  35376. */
  35377. set: function (value) {
  35378. if (this._alphaMode === value) {
  35379. return;
  35380. }
  35381. this._alphaMode = value;
  35382. this.markAsDirty(Material.TextureDirtyFlag);
  35383. },
  35384. enumerable: true,
  35385. configurable: true
  35386. });
  35387. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35388. /**
  35389. * Gets the depth pre-pass value
  35390. */
  35391. get: function () {
  35392. return this._needDepthPrePass;
  35393. },
  35394. /**
  35395. * Sets the need depth pre-pass value
  35396. */
  35397. set: function (value) {
  35398. if (this._needDepthPrePass === value) {
  35399. return;
  35400. }
  35401. this._needDepthPrePass = value;
  35402. if (this._needDepthPrePass) {
  35403. this.checkReadyOnEveryCall = true;
  35404. }
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(Material.prototype, "fogEnabled", {
  35410. /**
  35411. * Gets the value of the fog enabled state
  35412. */
  35413. get: function () {
  35414. return this._fogEnabled;
  35415. },
  35416. /**
  35417. * Sets the state for enabling fog
  35418. */
  35419. set: function (value) {
  35420. if (this._fogEnabled === value) {
  35421. return;
  35422. }
  35423. this._fogEnabled = value;
  35424. this.markAsDirty(Material.MiscDirtyFlag);
  35425. },
  35426. enumerable: true,
  35427. configurable: true
  35428. });
  35429. Object.defineProperty(Material.prototype, "wireframe", {
  35430. /**
  35431. * Gets a value specifying if wireframe mode is enabled
  35432. */
  35433. get: function () {
  35434. switch (this._fillMode) {
  35435. case Material.WireFrameFillMode:
  35436. case Material.LineListDrawMode:
  35437. case Material.LineLoopDrawMode:
  35438. case Material.LineStripDrawMode:
  35439. return true;
  35440. }
  35441. return this._scene.forceWireframe;
  35442. },
  35443. /**
  35444. * Sets the state of wireframe mode
  35445. */
  35446. set: function (value) {
  35447. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35448. },
  35449. enumerable: true,
  35450. configurable: true
  35451. });
  35452. Object.defineProperty(Material.prototype, "pointsCloud", {
  35453. /**
  35454. * Gets the value specifying if point clouds are enabled
  35455. */
  35456. get: function () {
  35457. switch (this._fillMode) {
  35458. case Material.PointFillMode:
  35459. case Material.PointListDrawMode:
  35460. return true;
  35461. }
  35462. return this._scene.forcePointsCloud;
  35463. },
  35464. /**
  35465. * Sets the state of point cloud mode
  35466. */
  35467. set: function (value) {
  35468. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35469. },
  35470. enumerable: true,
  35471. configurable: true
  35472. });
  35473. Object.defineProperty(Material.prototype, "fillMode", {
  35474. /**
  35475. * Gets the material fill mode
  35476. */
  35477. get: function () {
  35478. return this._fillMode;
  35479. },
  35480. /**
  35481. * Sets the material fill mode
  35482. */
  35483. set: function (value) {
  35484. if (this._fillMode === value) {
  35485. return;
  35486. }
  35487. this._fillMode = value;
  35488. this.markAsDirty(Material.MiscDirtyFlag);
  35489. },
  35490. enumerable: true,
  35491. configurable: true
  35492. });
  35493. /**
  35494. * Returns a string representation of the current material
  35495. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35496. * @returns a string with material information
  35497. */
  35498. Material.prototype.toString = function (fullDetails) {
  35499. var ret = "Name: " + this.name;
  35500. if (fullDetails) {
  35501. }
  35502. return ret;
  35503. };
  35504. /**
  35505. * Gets the class name of the material
  35506. * @returns a string with the class name of the material
  35507. */
  35508. Material.prototype.getClassName = function () {
  35509. return "Material";
  35510. };
  35511. Object.defineProperty(Material.prototype, "isFrozen", {
  35512. /**
  35513. * Specifies if updates for the material been locked
  35514. */
  35515. get: function () {
  35516. return this.checkReadyOnlyOnce;
  35517. },
  35518. enumerable: true,
  35519. configurable: true
  35520. });
  35521. /**
  35522. * Locks updates for the material
  35523. */
  35524. Material.prototype.freeze = function () {
  35525. this.checkReadyOnlyOnce = true;
  35526. };
  35527. /**
  35528. * Unlocks updates for the material
  35529. */
  35530. Material.prototype.unfreeze = function () {
  35531. this.checkReadyOnlyOnce = false;
  35532. };
  35533. /**
  35534. * Specifies if the material is ready to be used
  35535. * @param mesh defines the mesh to check
  35536. * @param useInstances specifies if instances should be used
  35537. * @returns a boolean indicating if the material is ready to be used
  35538. */
  35539. Material.prototype.isReady = function (mesh, useInstances) {
  35540. return true;
  35541. };
  35542. /**
  35543. * Specifies that the submesh is ready to be used
  35544. * @param mesh defines the mesh to check
  35545. * @param subMesh defines which submesh to check
  35546. * @param useInstances specifies that instances should be used
  35547. * @returns a boolean indicating that the submesh is ready or not
  35548. */
  35549. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35550. return false;
  35551. };
  35552. /**
  35553. * Returns the material effect
  35554. * @returns the effect associated with the material
  35555. */
  35556. Material.prototype.getEffect = function () {
  35557. return this._effect;
  35558. };
  35559. /**
  35560. * Returns the current scene
  35561. * @returns a Scene
  35562. */
  35563. Material.prototype.getScene = function () {
  35564. return this._scene;
  35565. };
  35566. /**
  35567. * Specifies if the material will require alpha blending
  35568. * @returns a boolean specifying if alpha blending is needed
  35569. */
  35570. Material.prototype.needAlphaBlending = function () {
  35571. return (this.alpha < 1.0);
  35572. };
  35573. /**
  35574. * Specifies if the mesh will require alpha blending
  35575. * @param mesh defines the mesh to check
  35576. * @returns a boolean specifying if alpha blending is needed for the mesh
  35577. */
  35578. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35579. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35580. };
  35581. /**
  35582. * Specifies if this material should be rendered in alpha test mode
  35583. * @returns a boolean specifying if an alpha test is needed.
  35584. */
  35585. Material.prototype.needAlphaTesting = function () {
  35586. return false;
  35587. };
  35588. /**
  35589. * Gets the texture used for the alpha test
  35590. * @returns the texture to use for alpha testing
  35591. */
  35592. Material.prototype.getAlphaTestTexture = function () {
  35593. return null;
  35594. };
  35595. /**
  35596. * Marks the material to indicate that it needs to be re-calculated
  35597. */
  35598. Material.prototype.markDirty = function () {
  35599. this._wasPreviouslyReady = false;
  35600. };
  35601. /** @hidden */
  35602. Material.prototype._preBind = function (effect, overrideOrientation) {
  35603. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35604. var engine = this._scene.getEngine();
  35605. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35606. var reverse = orientation === Material.ClockWiseSideOrientation;
  35607. engine.enableEffect(effect ? effect : this._effect);
  35608. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35609. return reverse;
  35610. };
  35611. /**
  35612. * Binds the material to the mesh
  35613. * @param world defines the world transformation matrix
  35614. * @param mesh defines the mesh to bind the material to
  35615. */
  35616. Material.prototype.bind = function (world, mesh) {
  35617. };
  35618. /**
  35619. * Binds the submesh to the material
  35620. * @param world defines the world transformation matrix
  35621. * @param mesh defines the mesh containing the submesh
  35622. * @param subMesh defines the submesh to bind the material to
  35623. */
  35624. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35625. };
  35626. /**
  35627. * Binds the world matrix to the material
  35628. * @param world defines the world transformation matrix
  35629. */
  35630. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35631. };
  35632. /**
  35633. * Binds the scene's uniform buffer to the effect.
  35634. * @param effect defines the effect to bind to the scene uniform buffer
  35635. * @param sceneUbo defines the uniform buffer storing scene data
  35636. */
  35637. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35638. sceneUbo.bindToEffect(effect, "Scene");
  35639. };
  35640. /**
  35641. * Binds the view matrix to the effect
  35642. * @param effect defines the effect to bind the view matrix to
  35643. */
  35644. Material.prototype.bindView = function (effect) {
  35645. if (!this._useUBO) {
  35646. effect.setMatrix("view", this.getScene().getViewMatrix());
  35647. }
  35648. else {
  35649. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35650. }
  35651. };
  35652. /**
  35653. * Binds the view projection matrix to the effect
  35654. * @param effect defines the effect to bind the view projection matrix to
  35655. */
  35656. Material.prototype.bindViewProjection = function (effect) {
  35657. if (!this._useUBO) {
  35658. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35659. }
  35660. else {
  35661. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35662. }
  35663. };
  35664. /**
  35665. * Specifies if material alpha testing should be turned on for the mesh
  35666. * @param mesh defines the mesh to check
  35667. */
  35668. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35669. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35670. };
  35671. /**
  35672. * Processes to execute after binding the material to a mesh
  35673. * @param mesh defines the rendered mesh
  35674. */
  35675. Material.prototype._afterBind = function (mesh) {
  35676. this._scene._cachedMaterial = this;
  35677. if (mesh) {
  35678. this._scene._cachedVisibility = mesh.visibility;
  35679. }
  35680. else {
  35681. this._scene._cachedVisibility = 1;
  35682. }
  35683. if (mesh) {
  35684. this.onBindObservable.notifyObservers(mesh);
  35685. }
  35686. if (this.disableDepthWrite) {
  35687. var engine = this._scene.getEngine();
  35688. this._cachedDepthWriteState = engine.getDepthWrite();
  35689. engine.setDepthWrite(false);
  35690. }
  35691. };
  35692. /**
  35693. * Unbinds the material from the mesh
  35694. */
  35695. Material.prototype.unbind = function () {
  35696. this.onUnBindObservable.notifyObservers(this);
  35697. if (this.disableDepthWrite) {
  35698. var engine = this._scene.getEngine();
  35699. engine.setDepthWrite(this._cachedDepthWriteState);
  35700. }
  35701. };
  35702. /**
  35703. * Gets the active textures from the material
  35704. * @returns an array of textures
  35705. */
  35706. Material.prototype.getActiveTextures = function () {
  35707. return [];
  35708. };
  35709. /**
  35710. * Specifies if the material uses a texture
  35711. * @param texture defines the texture to check against the material
  35712. * @returns a boolean specifying if the material uses the texture
  35713. */
  35714. Material.prototype.hasTexture = function (texture) {
  35715. return false;
  35716. };
  35717. /**
  35718. * Makes a duplicate of the material, and gives it a new name
  35719. * @param name defines the new name for the duplicated material
  35720. * @returns the cloned material
  35721. */
  35722. Material.prototype.clone = function (name) {
  35723. return null;
  35724. };
  35725. /**
  35726. * Gets the meshes bound to the material
  35727. * @returns an array of meshes bound to the material
  35728. */
  35729. Material.prototype.getBindedMeshes = function () {
  35730. var result = new Array();
  35731. for (var index = 0; index < this._scene.meshes.length; index++) {
  35732. var mesh = this._scene.meshes[index];
  35733. if (mesh.material === this) {
  35734. result.push(mesh);
  35735. }
  35736. }
  35737. return result;
  35738. };
  35739. /**
  35740. * Force shader compilation
  35741. * @param mesh defines the mesh associated with this material
  35742. * @param onCompiled defines a function to execute once the material is compiled
  35743. * @param options defines the options to configure the compilation
  35744. */
  35745. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35746. var _this = this;
  35747. var localOptions = __assign({ clipPlane: false }, options);
  35748. var subMesh = new BABYLON.BaseSubMesh();
  35749. var scene = this.getScene();
  35750. var checkReady = function () {
  35751. if (!_this._scene || !_this._scene.getEngine()) {
  35752. return;
  35753. }
  35754. if (subMesh._materialDefines) {
  35755. subMesh._materialDefines._renderId = -1;
  35756. }
  35757. var clipPlaneState = scene.clipPlane;
  35758. if (localOptions.clipPlane) {
  35759. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35760. }
  35761. if (_this.storeEffectOnSubMeshes) {
  35762. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35763. if (onCompiled) {
  35764. onCompiled(_this);
  35765. }
  35766. }
  35767. else {
  35768. setTimeout(checkReady, 16);
  35769. }
  35770. }
  35771. else {
  35772. if (_this.isReady(mesh)) {
  35773. if (onCompiled) {
  35774. onCompiled(_this);
  35775. }
  35776. }
  35777. else {
  35778. setTimeout(checkReady, 16);
  35779. }
  35780. }
  35781. if (localOptions.clipPlane) {
  35782. scene.clipPlane = clipPlaneState;
  35783. }
  35784. };
  35785. checkReady();
  35786. };
  35787. /**
  35788. * Force shader compilation
  35789. * @param mesh defines the mesh that will use this material
  35790. * @param options defines additional options for compiling the shaders
  35791. * @returns a promise that resolves when the compilation completes
  35792. */
  35793. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35794. var _this = this;
  35795. return new Promise(function (resolve) {
  35796. _this.forceCompilation(mesh, function () {
  35797. resolve();
  35798. }, options);
  35799. });
  35800. };
  35801. /**
  35802. * Marks a define in the material to indicate that it needs to be re-computed
  35803. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35804. */
  35805. Material.prototype.markAsDirty = function (flag) {
  35806. if (flag & Material.TextureDirtyFlag) {
  35807. this._markAllSubMeshesAsTexturesDirty();
  35808. }
  35809. if (flag & Material.LightDirtyFlag) {
  35810. this._markAllSubMeshesAsLightsDirty();
  35811. }
  35812. if (flag & Material.FresnelDirtyFlag) {
  35813. this._markAllSubMeshesAsFresnelDirty();
  35814. }
  35815. if (flag & Material.AttributesDirtyFlag) {
  35816. this._markAllSubMeshesAsAttributesDirty();
  35817. }
  35818. if (flag & Material.MiscDirtyFlag) {
  35819. this._markAllSubMeshesAsMiscDirty();
  35820. }
  35821. this.getScene().resetCachedMaterial();
  35822. };
  35823. /**
  35824. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35825. * @param func defines a function which checks material defines against the submeshes
  35826. */
  35827. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35828. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35829. var mesh = _a[_i];
  35830. if (!mesh.subMeshes) {
  35831. continue;
  35832. }
  35833. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35834. var subMesh = _c[_b];
  35835. if (subMesh.getMaterial() !== this) {
  35836. continue;
  35837. }
  35838. if (!subMesh._materialDefines) {
  35839. continue;
  35840. }
  35841. func(subMesh._materialDefines);
  35842. }
  35843. }
  35844. };
  35845. /**
  35846. * Indicates that image processing needs to be re-calculated for all submeshes
  35847. */
  35848. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35849. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35850. };
  35851. /**
  35852. * Indicates that textures need to be re-calculated for all submeshes
  35853. */
  35854. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35855. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35856. };
  35857. /**
  35858. * Indicates that fresnel needs to be re-calculated for all submeshes
  35859. */
  35860. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35861. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35862. };
  35863. /**
  35864. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35865. */
  35866. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35867. this._markAllSubMeshesAsDirty(function (defines) {
  35868. defines.markAsFresnelDirty();
  35869. defines.markAsMiscDirty();
  35870. });
  35871. };
  35872. /**
  35873. * Indicates that lights need to be re-calculated for all submeshes
  35874. */
  35875. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35876. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35877. };
  35878. /**
  35879. * Indicates that attributes need to be re-calculated for all submeshes
  35880. */
  35881. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35882. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35883. };
  35884. /**
  35885. * Indicates that misc needs to be re-calculated for all submeshes
  35886. */
  35887. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35888. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35889. };
  35890. /**
  35891. * Indicates that textures and misc need to be re-calculated for all submeshes
  35892. */
  35893. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35894. this._markAllSubMeshesAsDirty(function (defines) {
  35895. defines.markAsTexturesDirty();
  35896. defines.markAsMiscDirty();
  35897. });
  35898. };
  35899. /**
  35900. * Disposes the material
  35901. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35902. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35903. */
  35904. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35905. // Animations
  35906. this.getScene().stopAnimation(this);
  35907. this.getScene().freeProcessedMaterials();
  35908. // Remove from scene
  35909. var index = this._scene.materials.indexOf(this);
  35910. if (index >= 0) {
  35911. this._scene.materials.splice(index, 1);
  35912. }
  35913. // Remove from meshes
  35914. for (index = 0; index < this._scene.meshes.length; index++) {
  35915. var mesh = this._scene.meshes[index];
  35916. if (mesh.material === this) {
  35917. mesh.material = null;
  35918. if (mesh.geometry) {
  35919. var geometry = (mesh.geometry);
  35920. if (this.storeEffectOnSubMeshes) {
  35921. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35922. var subMesh = _a[_i];
  35923. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35924. if (forceDisposeEffect && subMesh._materialEffect) {
  35925. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35926. }
  35927. }
  35928. }
  35929. else {
  35930. geometry._releaseVertexArrayObject(this._effect);
  35931. }
  35932. }
  35933. }
  35934. }
  35935. this._uniformBuffer.dispose();
  35936. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35937. if (forceDisposeEffect && this._effect) {
  35938. if (!this.storeEffectOnSubMeshes) {
  35939. this._scene.getEngine()._releaseEffect(this._effect);
  35940. }
  35941. this._effect = null;
  35942. }
  35943. // Callback
  35944. this.onDisposeObservable.notifyObservers(this);
  35945. this.onDisposeObservable.clear();
  35946. this.onBindObservable.clear();
  35947. this.onUnBindObservable.clear();
  35948. };
  35949. /**
  35950. * Serializes this material
  35951. * @returns the serialized material object
  35952. */
  35953. Material.prototype.serialize = function () {
  35954. return BABYLON.SerializationHelper.Serialize(this);
  35955. };
  35956. /**
  35957. * Creates a MultiMaterial from parsed MultiMaterial data.
  35958. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35959. * @param scene defines the hosting scene
  35960. * @returns a new MultiMaterial
  35961. */
  35962. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35963. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35964. multiMaterial.id = parsedMultiMaterial.id;
  35965. if (BABYLON.Tags) {
  35966. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35967. }
  35968. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35969. var subMatId = parsedMultiMaterial.materials[matIndex];
  35970. if (subMatId) {
  35971. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35972. }
  35973. else {
  35974. multiMaterial.subMaterials.push(null);
  35975. }
  35976. }
  35977. return multiMaterial;
  35978. };
  35979. /**
  35980. * Creates a material from parsed material data
  35981. * @param parsedMaterial defines parsed material data
  35982. * @param scene defines the hosting scene
  35983. * @param rootUrl defines the root URL to use to load textures
  35984. * @returns a new material
  35985. */
  35986. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35987. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35988. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35989. }
  35990. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35991. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35992. if (!BABYLON.LegacyPBRMaterial) {
  35993. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35994. return;
  35995. }
  35996. }
  35997. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35998. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35999. };
  36000. // Triangle views
  36001. Material._TriangleFillMode = 0;
  36002. Material._WireFrameFillMode = 1;
  36003. Material._PointFillMode = 2;
  36004. // Draw modes
  36005. Material._PointListDrawMode = 3;
  36006. Material._LineListDrawMode = 4;
  36007. Material._LineLoopDrawMode = 5;
  36008. Material._LineStripDrawMode = 6;
  36009. Material._TriangleStripDrawMode = 7;
  36010. Material._TriangleFanDrawMode = 8;
  36011. /**
  36012. * Stores the clock-wise side orientation
  36013. */
  36014. Material._ClockWiseSideOrientation = 0;
  36015. /**
  36016. * Stores the counter clock-wise side orientation
  36017. */
  36018. Material._CounterClockWiseSideOrientation = 1;
  36019. /**
  36020. * The dirty texture flag value
  36021. */
  36022. Material._TextureDirtyFlag = 1;
  36023. /**
  36024. * The dirty light flag value
  36025. */
  36026. Material._LightDirtyFlag = 2;
  36027. /**
  36028. * The dirty fresnel flag value
  36029. */
  36030. Material._FresnelDirtyFlag = 4;
  36031. /**
  36032. * The dirty attribute flag value
  36033. */
  36034. Material._AttributesDirtyFlag = 8;
  36035. /**
  36036. * The dirty misc flag value
  36037. */
  36038. Material._MiscDirtyFlag = 16;
  36039. __decorate([
  36040. BABYLON.serialize()
  36041. ], Material.prototype, "id", void 0);
  36042. __decorate([
  36043. BABYLON.serialize()
  36044. ], Material.prototype, "uniqueId", void 0);
  36045. __decorate([
  36046. BABYLON.serialize()
  36047. ], Material.prototype, "name", void 0);
  36048. __decorate([
  36049. BABYLON.serialize()
  36050. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36051. __decorate([
  36052. BABYLON.serialize()
  36053. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36054. __decorate([
  36055. BABYLON.serialize()
  36056. ], Material.prototype, "state", void 0);
  36057. __decorate([
  36058. BABYLON.serialize("alpha")
  36059. ], Material.prototype, "_alpha", void 0);
  36060. __decorate([
  36061. BABYLON.serialize("backFaceCulling")
  36062. ], Material.prototype, "_backFaceCulling", void 0);
  36063. __decorate([
  36064. BABYLON.serialize()
  36065. ], Material.prototype, "sideOrientation", void 0);
  36066. __decorate([
  36067. BABYLON.serialize("alphaMode")
  36068. ], Material.prototype, "_alphaMode", void 0);
  36069. __decorate([
  36070. BABYLON.serialize()
  36071. ], Material.prototype, "_needDepthPrePass", void 0);
  36072. __decorate([
  36073. BABYLON.serialize()
  36074. ], Material.prototype, "disableDepthWrite", void 0);
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], Material.prototype, "forceDepthWrite", void 0);
  36078. __decorate([
  36079. BABYLON.serialize()
  36080. ], Material.prototype, "separateCullingPass", void 0);
  36081. __decorate([
  36082. BABYLON.serialize("fogEnabled")
  36083. ], Material.prototype, "_fogEnabled", void 0);
  36084. __decorate([
  36085. BABYLON.serialize()
  36086. ], Material.prototype, "pointSize", void 0);
  36087. __decorate([
  36088. BABYLON.serialize()
  36089. ], Material.prototype, "zOffset", void 0);
  36090. __decorate([
  36091. BABYLON.serialize()
  36092. ], Material.prototype, "wireframe", null);
  36093. __decorate([
  36094. BABYLON.serialize()
  36095. ], Material.prototype, "pointsCloud", null);
  36096. __decorate([
  36097. BABYLON.serialize()
  36098. ], Material.prototype, "fillMode", null);
  36099. return Material;
  36100. }());
  36101. BABYLON.Material = Material;
  36102. })(BABYLON || (BABYLON = {}));
  36103. //# sourceMappingURL=babylon.material.js.map
  36104. var BABYLON;
  36105. (function (BABYLON) {
  36106. var UniformBuffer = /** @class */ (function () {
  36107. /**
  36108. * Uniform buffer objects.
  36109. *
  36110. * Handles blocks of uniform on the GPU.
  36111. *
  36112. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36113. *
  36114. * For more information, please refer to :
  36115. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36116. */
  36117. function UniformBuffer(engine, data, dynamic) {
  36118. this._engine = engine;
  36119. this._noUBO = !engine.supportsUniformBuffers;
  36120. this._dynamic = dynamic;
  36121. this._data = data || [];
  36122. this._uniformLocations = {};
  36123. this._uniformSizes = {};
  36124. this._uniformLocationPointer = 0;
  36125. this._needSync = false;
  36126. if (this._noUBO) {
  36127. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36128. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36129. this.updateFloat = this._updateFloatForEffect;
  36130. this.updateFloat2 = this._updateFloat2ForEffect;
  36131. this.updateFloat3 = this._updateFloat3ForEffect;
  36132. this.updateFloat4 = this._updateFloat4ForEffect;
  36133. this.updateMatrix = this._updateMatrixForEffect;
  36134. this.updateVector3 = this._updateVector3ForEffect;
  36135. this.updateVector4 = this._updateVector4ForEffect;
  36136. this.updateColor3 = this._updateColor3ForEffect;
  36137. this.updateColor4 = this._updateColor4ForEffect;
  36138. }
  36139. else {
  36140. this._engine._uniformBuffers.push(this);
  36141. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36142. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36143. this.updateFloat = this._updateFloatForUniform;
  36144. this.updateFloat2 = this._updateFloat2ForUniform;
  36145. this.updateFloat3 = this._updateFloat3ForUniform;
  36146. this.updateFloat4 = this._updateFloat4ForUniform;
  36147. this.updateMatrix = this._updateMatrixForUniform;
  36148. this.updateVector3 = this._updateVector3ForUniform;
  36149. this.updateVector4 = this._updateVector4ForUniform;
  36150. this.updateColor3 = this._updateColor3ForUniform;
  36151. this.updateColor4 = this._updateColor4ForUniform;
  36152. }
  36153. }
  36154. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36155. // Properties
  36156. /**
  36157. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36158. * or just falling back on setUniformXXX calls.
  36159. */
  36160. get: function () {
  36161. return !this._noUBO;
  36162. },
  36163. enumerable: true,
  36164. configurable: true
  36165. });
  36166. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36167. /**
  36168. * Indicates if the WebGL underlying uniform buffer is in sync
  36169. * with the javascript cache data.
  36170. */
  36171. get: function () {
  36172. return !this._needSync;
  36173. },
  36174. enumerable: true,
  36175. configurable: true
  36176. });
  36177. /**
  36178. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36179. * Also, a dynamic UniformBuffer will disable cache verification and always
  36180. * update the underlying WebGL uniform buffer to the GPU.
  36181. */
  36182. UniformBuffer.prototype.isDynamic = function () {
  36183. return this._dynamic !== undefined;
  36184. };
  36185. /**
  36186. * The data cache on JS side.
  36187. */
  36188. UniformBuffer.prototype.getData = function () {
  36189. return this._bufferData;
  36190. };
  36191. /**
  36192. * The underlying WebGL Uniform buffer.
  36193. */
  36194. UniformBuffer.prototype.getBuffer = function () {
  36195. return this._buffer;
  36196. };
  36197. /**
  36198. * std140 layout specifies how to align data within an UBO structure.
  36199. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36200. * for specs.
  36201. */
  36202. UniformBuffer.prototype._fillAlignment = function (size) {
  36203. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36204. // and 4x4 matrices
  36205. // TODO : change if other types are used
  36206. var alignment;
  36207. if (size <= 2) {
  36208. alignment = size;
  36209. }
  36210. else {
  36211. alignment = 4;
  36212. }
  36213. if ((this._uniformLocationPointer % alignment) !== 0) {
  36214. var oldPointer = this._uniformLocationPointer;
  36215. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36216. var diff = this._uniformLocationPointer - oldPointer;
  36217. for (var i = 0; i < diff; i++) {
  36218. this._data.push(0);
  36219. }
  36220. }
  36221. };
  36222. /**
  36223. * Adds an uniform in the buffer.
  36224. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36225. * for the layout to be correct !
  36226. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36227. * @param {number|number[]} size Data size, or data directly.
  36228. */
  36229. UniformBuffer.prototype.addUniform = function (name, size) {
  36230. if (this._noUBO) {
  36231. return;
  36232. }
  36233. if (this._uniformLocations[name] !== undefined) {
  36234. // Already existing uniform
  36235. return;
  36236. }
  36237. // This function must be called in the order of the shader layout !
  36238. // size can be the size of the uniform, or data directly
  36239. var data;
  36240. if (size instanceof Array) {
  36241. data = size;
  36242. size = data.length;
  36243. }
  36244. else {
  36245. size = size;
  36246. data = [];
  36247. // Fill with zeros
  36248. for (var i = 0; i < size; i++) {
  36249. data.push(0);
  36250. }
  36251. }
  36252. this._fillAlignment(size);
  36253. this._uniformSizes[name] = size;
  36254. this._uniformLocations[name] = this._uniformLocationPointer;
  36255. this._uniformLocationPointer += size;
  36256. for (var i = 0; i < size; i++) {
  36257. this._data.push(data[i]);
  36258. }
  36259. this._needSync = true;
  36260. };
  36261. /**
  36262. * Wrapper for addUniform.
  36263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36264. * @param {Matrix} mat A 4x4 matrix.
  36265. */
  36266. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36267. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36268. };
  36269. /**
  36270. * Wrapper for addUniform.
  36271. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36272. * @param {number} x
  36273. * @param {number} y
  36274. */
  36275. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36276. var temp = [x, y];
  36277. this.addUniform(name, temp);
  36278. };
  36279. /**
  36280. * Wrapper for addUniform.
  36281. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36282. * @param {number} x
  36283. * @param {number} y
  36284. * @param {number} z
  36285. */
  36286. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36287. var temp = [x, y, z];
  36288. this.addUniform(name, temp);
  36289. };
  36290. /**
  36291. * Wrapper for addUniform.
  36292. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36293. * @param {Color3} color
  36294. */
  36295. UniformBuffer.prototype.addColor3 = function (name, color) {
  36296. var temp = new Array();
  36297. color.toArray(temp);
  36298. this.addUniform(name, temp);
  36299. };
  36300. /**
  36301. * Wrapper for addUniform.
  36302. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36303. * @param {Color3} color
  36304. * @param {number} alpha
  36305. */
  36306. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36307. var temp = new Array();
  36308. color.toArray(temp);
  36309. temp.push(alpha);
  36310. this.addUniform(name, temp);
  36311. };
  36312. /**
  36313. * Wrapper for addUniform.
  36314. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36315. * @param {Vector3} vector
  36316. */
  36317. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36318. var temp = new Array();
  36319. vector.toArray(temp);
  36320. this.addUniform(name, temp);
  36321. };
  36322. /**
  36323. * Wrapper for addUniform.
  36324. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36325. */
  36326. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36327. this.addUniform(name, 12);
  36328. };
  36329. /**
  36330. * Wrapper for addUniform.
  36331. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36332. */
  36333. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36334. this.addUniform(name, 8);
  36335. };
  36336. /**
  36337. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36338. */
  36339. UniformBuffer.prototype.create = function () {
  36340. if (this._noUBO) {
  36341. return;
  36342. }
  36343. if (this._buffer) {
  36344. return; // nothing to do
  36345. }
  36346. // See spec, alignment must be filled as a vec4
  36347. this._fillAlignment(4);
  36348. this._bufferData = new Float32Array(this._data);
  36349. this._rebuild();
  36350. this._needSync = true;
  36351. };
  36352. UniformBuffer.prototype._rebuild = function () {
  36353. if (this._noUBO) {
  36354. return;
  36355. }
  36356. if (this._dynamic) {
  36357. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36358. }
  36359. else {
  36360. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36361. }
  36362. };
  36363. /**
  36364. * Updates the WebGL Uniform Buffer on the GPU.
  36365. * If the `dynamic` flag is set to true, no cache comparison is done.
  36366. * Otherwise, the buffer will be updated only if the cache differs.
  36367. */
  36368. UniformBuffer.prototype.update = function () {
  36369. if (!this._buffer) {
  36370. this.create();
  36371. return;
  36372. }
  36373. if (!this._dynamic && !this._needSync) {
  36374. return;
  36375. }
  36376. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36377. this._needSync = false;
  36378. };
  36379. /**
  36380. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36381. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36382. * @param {number[]|Float32Array} data Flattened data
  36383. * @param {number} size Size of the data.
  36384. */
  36385. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36386. var location = this._uniformLocations[uniformName];
  36387. if (location === undefined) {
  36388. if (this._buffer) {
  36389. // Cannot add an uniform if the buffer is already created
  36390. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36391. return;
  36392. }
  36393. this.addUniform(uniformName, size);
  36394. location = this._uniformLocations[uniformName];
  36395. }
  36396. if (!this._buffer) {
  36397. this.create();
  36398. }
  36399. if (!this._dynamic) {
  36400. // Cache for static uniform buffers
  36401. var changed = false;
  36402. for (var i = 0; i < size; i++) {
  36403. if (this._bufferData[location + i] !== data[i]) {
  36404. changed = true;
  36405. this._bufferData[location + i] = data[i];
  36406. }
  36407. }
  36408. this._needSync = this._needSync || changed;
  36409. }
  36410. else {
  36411. // No cache for dynamic
  36412. for (var i = 0; i < size; i++) {
  36413. this._bufferData[location + i] = data[i];
  36414. }
  36415. }
  36416. };
  36417. // Update methods
  36418. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36419. // To match std140, matrix must be realigned
  36420. for (var i = 0; i < 3; i++) {
  36421. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36422. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36423. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36424. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36425. }
  36426. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36427. };
  36428. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36429. this._currentEffect.setMatrix3x3(name, matrix);
  36430. };
  36431. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36432. this._currentEffect.setMatrix2x2(name, matrix);
  36433. };
  36434. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36435. // To match std140, matrix must be realigned
  36436. for (var i = 0; i < 2; i++) {
  36437. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36438. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36439. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36440. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36441. }
  36442. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36443. };
  36444. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36445. this._currentEffect.setFloat(name, x);
  36446. };
  36447. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36448. UniformBuffer._tempBuffer[0] = x;
  36449. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36450. };
  36451. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36452. if (suffix === void 0) { suffix = ""; }
  36453. this._currentEffect.setFloat2(name + suffix, x, y);
  36454. };
  36455. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36456. if (suffix === void 0) { suffix = ""; }
  36457. UniformBuffer._tempBuffer[0] = x;
  36458. UniformBuffer._tempBuffer[1] = y;
  36459. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36460. };
  36461. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36462. if (suffix === void 0) { suffix = ""; }
  36463. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36464. };
  36465. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36466. if (suffix === void 0) { suffix = ""; }
  36467. UniformBuffer._tempBuffer[0] = x;
  36468. UniformBuffer._tempBuffer[1] = y;
  36469. UniformBuffer._tempBuffer[2] = z;
  36470. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36471. };
  36472. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36473. if (suffix === void 0) { suffix = ""; }
  36474. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36475. };
  36476. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36477. if (suffix === void 0) { suffix = ""; }
  36478. UniformBuffer._tempBuffer[0] = x;
  36479. UniformBuffer._tempBuffer[1] = y;
  36480. UniformBuffer._tempBuffer[2] = z;
  36481. UniformBuffer._tempBuffer[3] = w;
  36482. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36483. };
  36484. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36485. this._currentEffect.setMatrix(name, mat);
  36486. };
  36487. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36488. this.updateUniform(name, mat.toArray(), 16);
  36489. };
  36490. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36491. this._currentEffect.setVector3(name, vector);
  36492. };
  36493. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36494. vector.toArray(UniformBuffer._tempBuffer);
  36495. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36496. };
  36497. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36498. this._currentEffect.setVector4(name, vector);
  36499. };
  36500. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36501. vector.toArray(UniformBuffer._tempBuffer);
  36502. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36503. };
  36504. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36505. if (suffix === void 0) { suffix = ""; }
  36506. this._currentEffect.setColor3(name + suffix, color);
  36507. };
  36508. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36509. if (suffix === void 0) { suffix = ""; }
  36510. color.toArray(UniformBuffer._tempBuffer);
  36511. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36512. };
  36513. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36514. if (suffix === void 0) { suffix = ""; }
  36515. this._currentEffect.setColor4(name + suffix, color, alpha);
  36516. };
  36517. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36518. if (suffix === void 0) { suffix = ""; }
  36519. color.toArray(UniformBuffer._tempBuffer);
  36520. UniformBuffer._tempBuffer[3] = alpha;
  36521. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36522. };
  36523. /**
  36524. * Sets a sampler uniform on the effect.
  36525. * @param {string} name Name of the sampler.
  36526. * @param {Texture} texture
  36527. */
  36528. UniformBuffer.prototype.setTexture = function (name, texture) {
  36529. this._currentEffect.setTexture(name, texture);
  36530. };
  36531. /**
  36532. * Directly updates the value of the uniform in the cache AND on the GPU.
  36533. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36534. * @param {number[]|Float32Array} data Flattened data
  36535. */
  36536. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36537. this.updateUniform(uniformName, data, data.length);
  36538. this.update();
  36539. };
  36540. /**
  36541. * Binds this uniform buffer to an effect.
  36542. * @param {Effect} effect
  36543. * @param {string} name Name of the uniform block in the shader.
  36544. */
  36545. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36546. this._currentEffect = effect;
  36547. if (this._noUBO || !this._buffer) {
  36548. return;
  36549. }
  36550. effect.bindUniformBuffer(this._buffer, name);
  36551. };
  36552. /**
  36553. * Disposes the uniform buffer.
  36554. */
  36555. UniformBuffer.prototype.dispose = function () {
  36556. if (this._noUBO) {
  36557. return;
  36558. }
  36559. var index = this._engine._uniformBuffers.indexOf(this);
  36560. if (index !== -1) {
  36561. this._engine._uniformBuffers.splice(index, 1);
  36562. }
  36563. if (!this._buffer) {
  36564. return;
  36565. }
  36566. if (this._engine._releaseBuffer(this._buffer)) {
  36567. this._buffer = null;
  36568. }
  36569. };
  36570. // Pool for avoiding memory leaks
  36571. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36572. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36573. return UniformBuffer;
  36574. }());
  36575. BABYLON.UniformBuffer = UniformBuffer;
  36576. })(BABYLON || (BABYLON = {}));
  36577. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36578. var BABYLON;
  36579. (function (BABYLON) {
  36580. /**
  36581. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36582. */
  36583. var VertexData = /** @class */ (function () {
  36584. function VertexData() {
  36585. }
  36586. /**
  36587. * Uses the passed data array to set the set the values for the specified kind of data
  36588. * @param data a linear array of floating numbers
  36589. * @param kind the type of data that is being set, eg positions, colors etc
  36590. */
  36591. VertexData.prototype.set = function (data, kind) {
  36592. switch (kind) {
  36593. case BABYLON.VertexBuffer.PositionKind:
  36594. this.positions = data;
  36595. break;
  36596. case BABYLON.VertexBuffer.NormalKind:
  36597. this.normals = data;
  36598. break;
  36599. case BABYLON.VertexBuffer.TangentKind:
  36600. this.tangents = data;
  36601. break;
  36602. case BABYLON.VertexBuffer.UVKind:
  36603. this.uvs = data;
  36604. break;
  36605. case BABYLON.VertexBuffer.UV2Kind:
  36606. this.uvs2 = data;
  36607. break;
  36608. case BABYLON.VertexBuffer.UV3Kind:
  36609. this.uvs3 = data;
  36610. break;
  36611. case BABYLON.VertexBuffer.UV4Kind:
  36612. this.uvs4 = data;
  36613. break;
  36614. case BABYLON.VertexBuffer.UV5Kind:
  36615. this.uvs5 = data;
  36616. break;
  36617. case BABYLON.VertexBuffer.UV6Kind:
  36618. this.uvs6 = data;
  36619. break;
  36620. case BABYLON.VertexBuffer.ColorKind:
  36621. this.colors = data;
  36622. break;
  36623. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36624. this.matricesIndices = data;
  36625. break;
  36626. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36627. this.matricesWeights = data;
  36628. break;
  36629. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36630. this.matricesIndicesExtra = data;
  36631. break;
  36632. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36633. this.matricesWeightsExtra = data;
  36634. break;
  36635. }
  36636. };
  36637. /**
  36638. * Associates the vertexData to the passed Mesh.
  36639. * Sets it as updatable or not (default `false`)
  36640. * @param mesh the mesh the vertexData is applied to
  36641. * @param updatable when used and having the value true allows new data to update the vertexData
  36642. * @returns the VertexData
  36643. */
  36644. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36645. this._applyTo(mesh, updatable);
  36646. return this;
  36647. };
  36648. /**
  36649. * Associates the vertexData to the passed Geometry.
  36650. * Sets it as updatable or not (default `false`)
  36651. * @param geometry the geometry the vertexData is applied to
  36652. * @param updatable when used and having the value true allows new data to update the vertexData
  36653. * @returns VertexData
  36654. */
  36655. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36656. this._applyTo(geometry, updatable);
  36657. return this;
  36658. };
  36659. /**
  36660. * Updates the associated mesh
  36661. * @param mesh the mesh to be updated
  36662. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36663. * @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
  36664. * @returns VertexData
  36665. */
  36666. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36667. this._update(mesh);
  36668. return this;
  36669. };
  36670. /**
  36671. * Updates the associated geometry
  36672. * @param geometry the geometry to be updated
  36673. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36674. * @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
  36675. * @returns VertexData.
  36676. */
  36677. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36678. this._update(geometry);
  36679. return this;
  36680. };
  36681. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36682. if (updatable === void 0) { updatable = false; }
  36683. if (this.positions) {
  36684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36685. }
  36686. if (this.normals) {
  36687. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36688. }
  36689. if (this.tangents) {
  36690. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36691. }
  36692. if (this.uvs) {
  36693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36694. }
  36695. if (this.uvs2) {
  36696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36697. }
  36698. if (this.uvs3) {
  36699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36700. }
  36701. if (this.uvs4) {
  36702. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36703. }
  36704. if (this.uvs5) {
  36705. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36706. }
  36707. if (this.uvs6) {
  36708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36709. }
  36710. if (this.colors) {
  36711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36712. }
  36713. if (this.matricesIndices) {
  36714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36715. }
  36716. if (this.matricesWeights) {
  36717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36718. }
  36719. if (this.matricesIndicesExtra) {
  36720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36721. }
  36722. if (this.matricesWeightsExtra) {
  36723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36724. }
  36725. if (this.indices) {
  36726. meshOrGeometry.setIndices(this.indices, null, updatable);
  36727. }
  36728. else {
  36729. meshOrGeometry.setIndices([], null);
  36730. }
  36731. return this;
  36732. };
  36733. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36734. if (this.positions) {
  36735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36736. }
  36737. if (this.normals) {
  36738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36739. }
  36740. if (this.tangents) {
  36741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36742. }
  36743. if (this.uvs) {
  36744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36745. }
  36746. if (this.uvs2) {
  36747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36748. }
  36749. if (this.uvs3) {
  36750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36751. }
  36752. if (this.uvs4) {
  36753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36754. }
  36755. if (this.uvs5) {
  36756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36757. }
  36758. if (this.uvs6) {
  36759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36760. }
  36761. if (this.colors) {
  36762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36763. }
  36764. if (this.matricesIndices) {
  36765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36766. }
  36767. if (this.matricesWeights) {
  36768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36769. }
  36770. if (this.matricesIndicesExtra) {
  36771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36772. }
  36773. if (this.matricesWeightsExtra) {
  36774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36775. }
  36776. if (this.indices) {
  36777. meshOrGeometry.setIndices(this.indices, null);
  36778. }
  36779. return this;
  36780. };
  36781. /**
  36782. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36783. * @param matrix the transforming matrix
  36784. * @returns the VertexData
  36785. */
  36786. VertexData.prototype.transform = function (matrix) {
  36787. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36788. var transformed = BABYLON.Vector3.Zero();
  36789. var index;
  36790. if (this.positions) {
  36791. var position = BABYLON.Vector3.Zero();
  36792. for (index = 0; index < this.positions.length; index += 3) {
  36793. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36794. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36795. this.positions[index] = transformed.x;
  36796. this.positions[index + 1] = transformed.y;
  36797. this.positions[index + 2] = transformed.z;
  36798. }
  36799. }
  36800. if (this.normals) {
  36801. var normal = BABYLON.Vector3.Zero();
  36802. for (index = 0; index < this.normals.length; index += 3) {
  36803. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36804. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36805. this.normals[index] = transformed.x;
  36806. this.normals[index + 1] = transformed.y;
  36807. this.normals[index + 2] = transformed.z;
  36808. }
  36809. }
  36810. if (this.tangents) {
  36811. var tangent = BABYLON.Vector4.Zero();
  36812. var tangentTransformed = BABYLON.Vector4.Zero();
  36813. for (index = 0; index < this.tangents.length; index += 4) {
  36814. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36815. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36816. this.tangents[index] = tangentTransformed.x;
  36817. this.tangents[index + 1] = tangentTransformed.y;
  36818. this.tangents[index + 2] = tangentTransformed.z;
  36819. this.tangents[index + 3] = tangentTransformed.w;
  36820. }
  36821. }
  36822. if (flip && this.indices) {
  36823. for (index = 0; index < this.indices.length; index += 3) {
  36824. var tmp = this.indices[index + 1];
  36825. this.indices[index + 1] = this.indices[index + 2];
  36826. this.indices[index + 2] = tmp;
  36827. }
  36828. }
  36829. return this;
  36830. };
  36831. /**
  36832. * Merges the passed VertexData into the current one
  36833. * @param other the VertexData to be merged into the current one
  36834. * @returns the modified VertexData
  36835. */
  36836. VertexData.prototype.merge = function (other) {
  36837. this._validate();
  36838. other._validate();
  36839. if (!this.normals !== !other.normals ||
  36840. !this.tangents !== !other.tangents ||
  36841. !this.uvs !== !other.uvs ||
  36842. !this.uvs2 !== !other.uvs2 ||
  36843. !this.uvs3 !== !other.uvs3 ||
  36844. !this.uvs4 !== !other.uvs4 ||
  36845. !this.uvs5 !== !other.uvs5 ||
  36846. !this.uvs6 !== !other.uvs6 ||
  36847. !this.colors !== !other.colors ||
  36848. !this.matricesIndices !== !other.matricesIndices ||
  36849. !this.matricesWeights !== !other.matricesWeights ||
  36850. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36851. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36852. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36853. }
  36854. if (other.indices) {
  36855. if (!this.indices) {
  36856. this.indices = [];
  36857. }
  36858. var offset = this.positions ? this.positions.length / 3 : 0;
  36859. for (var index = 0; index < other.indices.length; index++) {
  36860. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36861. this.indices.push(other.indices[index] + offset);
  36862. }
  36863. }
  36864. this.positions = this._mergeElement(this.positions, other.positions);
  36865. this.normals = this._mergeElement(this.normals, other.normals);
  36866. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36867. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36868. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36869. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36870. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36871. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36872. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36873. this.colors = this._mergeElement(this.colors, other.colors);
  36874. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36875. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36876. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36877. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36878. return this;
  36879. };
  36880. VertexData.prototype._mergeElement = function (source, other) {
  36881. if (!source) {
  36882. return other;
  36883. }
  36884. if (!other) {
  36885. return source;
  36886. }
  36887. var len = other.length + source.length;
  36888. var isSrcTypedArray = source instanceof Float32Array;
  36889. var isOthTypedArray = other instanceof Float32Array;
  36890. // use non-loop method when the source is Float32Array
  36891. if (isSrcTypedArray) {
  36892. var ret32 = new Float32Array(len);
  36893. ret32.set(source);
  36894. ret32.set(other, source.length);
  36895. return ret32;
  36896. // source is number[], when other is also use concat
  36897. }
  36898. else if (!isOthTypedArray) {
  36899. return source.concat(other);
  36900. // source is a number[], but other is a Float32Array, loop required
  36901. }
  36902. else {
  36903. var ret = source.slice(0); // copy source to a separate array
  36904. for (var i = 0, len = other.length; i < len; i++) {
  36905. ret.push(other[i]);
  36906. }
  36907. return ret;
  36908. }
  36909. };
  36910. VertexData.prototype._validate = function () {
  36911. if (!this.positions) {
  36912. throw new Error("Positions are required");
  36913. }
  36914. var getElementCount = function (kind, values) {
  36915. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36916. if ((values.length % stride) !== 0) {
  36917. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36918. }
  36919. return values.length / stride;
  36920. };
  36921. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36922. var validateElementCount = function (kind, values) {
  36923. var elementCount = getElementCount(kind, values);
  36924. if (elementCount !== positionsElementCount) {
  36925. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36926. }
  36927. };
  36928. if (this.normals)
  36929. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36930. if (this.tangents)
  36931. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36932. if (this.uvs)
  36933. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36934. if (this.uvs2)
  36935. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36936. if (this.uvs3)
  36937. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36938. if (this.uvs4)
  36939. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36940. if (this.uvs5)
  36941. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36942. if (this.uvs6)
  36943. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36944. if (this.colors)
  36945. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36946. if (this.matricesIndices)
  36947. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36948. if (this.matricesWeights)
  36949. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36950. if (this.matricesIndicesExtra)
  36951. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36952. if (this.matricesWeightsExtra)
  36953. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36954. };
  36955. /**
  36956. * Serializes the VertexData
  36957. * @returns a serialized object
  36958. */
  36959. VertexData.prototype.serialize = function () {
  36960. var serializationObject = this.serialize();
  36961. if (this.positions) {
  36962. serializationObject.positions = this.positions;
  36963. }
  36964. if (this.normals) {
  36965. serializationObject.normals = this.normals;
  36966. }
  36967. if (this.tangents) {
  36968. serializationObject.tangents = this.tangents;
  36969. }
  36970. if (this.uvs) {
  36971. serializationObject.uvs = this.uvs;
  36972. }
  36973. if (this.uvs2) {
  36974. serializationObject.uvs2 = this.uvs2;
  36975. }
  36976. if (this.uvs3) {
  36977. serializationObject.uvs3 = this.uvs3;
  36978. }
  36979. if (this.uvs4) {
  36980. serializationObject.uvs4 = this.uvs4;
  36981. }
  36982. if (this.uvs5) {
  36983. serializationObject.uvs5 = this.uvs5;
  36984. }
  36985. if (this.uvs6) {
  36986. serializationObject.uvs6 = this.uvs6;
  36987. }
  36988. if (this.colors) {
  36989. serializationObject.colors = this.colors;
  36990. }
  36991. if (this.matricesIndices) {
  36992. serializationObject.matricesIndices = this.matricesIndices;
  36993. serializationObject.matricesIndices._isExpanded = true;
  36994. }
  36995. if (this.matricesWeights) {
  36996. serializationObject.matricesWeights = this.matricesWeights;
  36997. }
  36998. if (this.matricesIndicesExtra) {
  36999. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37000. serializationObject.matricesIndicesExtra._isExpanded = true;
  37001. }
  37002. if (this.matricesWeightsExtra) {
  37003. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37004. }
  37005. serializationObject.indices = this.indices;
  37006. return serializationObject;
  37007. };
  37008. // Statics
  37009. /**
  37010. * Extracts the vertexData from a mesh
  37011. * @param mesh the mesh from which to extract the VertexData
  37012. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37013. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37014. * @returns the object VertexData associated to the passed mesh
  37015. */
  37016. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37017. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37018. };
  37019. /**
  37020. * Extracts the vertexData from the geometry
  37021. * @param geometry the geometry from which to extract the VertexData
  37022. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37023. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37024. * @returns the object VertexData associated to the passed mesh
  37025. */
  37026. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37027. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37028. };
  37029. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37030. var result = new VertexData();
  37031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37032. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37033. }
  37034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37035. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37036. }
  37037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37038. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37039. }
  37040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37041. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37042. }
  37043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37044. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37045. }
  37046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37047. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37048. }
  37049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37050. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37051. }
  37052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37053. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37054. }
  37055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37056. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37057. }
  37058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37059. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37060. }
  37061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37062. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37063. }
  37064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37065. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37066. }
  37067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37068. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37069. }
  37070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37071. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37072. }
  37073. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37074. return result;
  37075. };
  37076. /**
  37077. * Creates the VertexData for a Ribbon
  37078. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37079. * * pathArray array of paths, each of which an array of successive Vector3
  37080. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37081. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37082. * * 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
  37083. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37084. * * 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)
  37085. * * 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)
  37086. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37087. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37088. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37089. * @returns the VertexData of the ribbon
  37090. */
  37091. VertexData.CreateRibbon = function (options) {
  37092. var pathArray = options.pathArray;
  37093. var closeArray = options.closeArray || false;
  37094. var closePath = options.closePath || false;
  37095. var invertUV = options.invertUV || false;
  37096. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37097. var offset = options.offset || defaultOffset;
  37098. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37099. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37100. var customUV = options.uvs;
  37101. var customColors = options.colors;
  37102. var positions = [];
  37103. var indices = [];
  37104. var normals = [];
  37105. var uvs = [];
  37106. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37107. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37108. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37109. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37110. var minlg; // minimal length among all paths from pathArray
  37111. var lg = []; // array of path lengths : nb of vertex per path
  37112. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37113. var p; // path iterator
  37114. var i; // point iterator
  37115. var j; // point iterator
  37116. // if single path in pathArray
  37117. if (pathArray.length < 2) {
  37118. var ar1 = [];
  37119. var ar2 = [];
  37120. for (i = 0; i < pathArray[0].length - offset; i++) {
  37121. ar1.push(pathArray[0][i]);
  37122. ar2.push(pathArray[0][i + offset]);
  37123. }
  37124. pathArray = [ar1, ar2];
  37125. }
  37126. // positions and horizontal distances (u)
  37127. var idc = 0;
  37128. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37129. var path;
  37130. var l;
  37131. minlg = pathArray[0].length;
  37132. var vectlg;
  37133. var dist;
  37134. for (p = 0; p < pathArray.length; p++) {
  37135. uTotalDistance[p] = 0;
  37136. us[p] = [0];
  37137. path = pathArray[p];
  37138. l = path.length;
  37139. minlg = (minlg < l) ? minlg : l;
  37140. j = 0;
  37141. while (j < l) {
  37142. positions.push(path[j].x, path[j].y, path[j].z);
  37143. if (j > 0) {
  37144. vectlg = path[j].subtract(path[j - 1]).length();
  37145. dist = vectlg + uTotalDistance[p];
  37146. us[p].push(dist);
  37147. uTotalDistance[p] = dist;
  37148. }
  37149. j++;
  37150. }
  37151. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37152. j--;
  37153. positions.push(path[0].x, path[0].y, path[0].z);
  37154. vectlg = path[j].subtract(path[0]).length();
  37155. dist = vectlg + uTotalDistance[p];
  37156. us[p].push(dist);
  37157. uTotalDistance[p] = dist;
  37158. }
  37159. lg[p] = l + closePathCorr;
  37160. idx[p] = idc;
  37161. idc += (l + closePathCorr);
  37162. }
  37163. // vertical distances (v)
  37164. var path1;
  37165. var path2;
  37166. var vertex1 = null;
  37167. var vertex2 = null;
  37168. for (i = 0; i < minlg + closePathCorr; i++) {
  37169. vTotalDistance[i] = 0;
  37170. vs[i] = [0];
  37171. for (p = 0; p < pathArray.length - 1; p++) {
  37172. path1 = pathArray[p];
  37173. path2 = pathArray[p + 1];
  37174. if (i === minlg) { // closePath
  37175. vertex1 = path1[0];
  37176. vertex2 = path2[0];
  37177. }
  37178. else {
  37179. vertex1 = path1[i];
  37180. vertex2 = path2[i];
  37181. }
  37182. vectlg = vertex2.subtract(vertex1).length();
  37183. dist = vectlg + vTotalDistance[i];
  37184. vs[i].push(dist);
  37185. vTotalDistance[i] = dist;
  37186. }
  37187. if (closeArray && vertex2 && vertex1) {
  37188. path1 = pathArray[p];
  37189. path2 = pathArray[0];
  37190. if (i === minlg) { // closePath
  37191. vertex2 = path2[0];
  37192. }
  37193. vectlg = vertex2.subtract(vertex1).length();
  37194. dist = vectlg + vTotalDistance[i];
  37195. vTotalDistance[i] = dist;
  37196. }
  37197. }
  37198. // uvs
  37199. var u;
  37200. var v;
  37201. if (customUV) {
  37202. for (p = 0; p < customUV.length; p++) {
  37203. uvs.push(customUV[p].x, customUV[p].y);
  37204. }
  37205. }
  37206. else {
  37207. for (p = 0; p < pathArray.length; p++) {
  37208. for (i = 0; i < minlg + closePathCorr; i++) {
  37209. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37210. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37211. if (invertUV) {
  37212. uvs.push(v, u);
  37213. }
  37214. else {
  37215. uvs.push(u, v);
  37216. }
  37217. }
  37218. }
  37219. }
  37220. // indices
  37221. p = 0; // path index
  37222. var pi = 0; // positions array index
  37223. var l1 = lg[p] - 1; // path1 length
  37224. var l2 = lg[p + 1] - 1; // path2 length
  37225. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37226. var shft = idx[1] - idx[0]; // shift
  37227. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37228. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37229. // 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
  37230. indices.push(pi, pi + shft, pi + 1);
  37231. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37232. pi += 1;
  37233. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37234. p++;
  37235. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37236. shft = idx[0] - idx[p];
  37237. l1 = lg[p] - 1;
  37238. l2 = lg[0] - 1;
  37239. }
  37240. else {
  37241. shft = idx[p + 1] - idx[p];
  37242. l1 = lg[p] - 1;
  37243. l2 = lg[p + 1] - 1;
  37244. }
  37245. pi = idx[p];
  37246. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37247. }
  37248. }
  37249. // normals
  37250. VertexData.ComputeNormals(positions, indices, normals);
  37251. if (closePath) { // update both the first and last vertex normals to their average value
  37252. var indexFirst = 0;
  37253. var indexLast = 0;
  37254. for (p = 0; p < pathArray.length; p++) {
  37255. indexFirst = idx[p] * 3;
  37256. if (p + 1 < pathArray.length) {
  37257. indexLast = (idx[p + 1] - 1) * 3;
  37258. }
  37259. else {
  37260. indexLast = normals.length - 3;
  37261. }
  37262. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37263. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37264. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37265. normals[indexLast] = normals[indexFirst];
  37266. normals[indexLast + 1] = normals[indexFirst + 1];
  37267. normals[indexLast + 2] = normals[indexFirst + 2];
  37268. }
  37269. }
  37270. // sides
  37271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37272. // Colors
  37273. var colors = null;
  37274. if (customColors) {
  37275. colors = new Float32Array(customColors.length * 4);
  37276. for (var c = 0; c < customColors.length; c++) {
  37277. colors[c * 4] = customColors[c].r;
  37278. colors[c * 4 + 1] = customColors[c].g;
  37279. colors[c * 4 + 2] = customColors[c].b;
  37280. colors[c * 4 + 3] = customColors[c].a;
  37281. }
  37282. }
  37283. // Result
  37284. var vertexData = new VertexData();
  37285. var positions32 = new Float32Array(positions);
  37286. var normals32 = new Float32Array(normals);
  37287. var uvs32 = new Float32Array(uvs);
  37288. vertexData.indices = indices;
  37289. vertexData.positions = positions32;
  37290. vertexData.normals = normals32;
  37291. vertexData.uvs = uvs32;
  37292. if (colors) {
  37293. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37294. }
  37295. if (closePath) {
  37296. vertexData._idx = idx;
  37297. }
  37298. return vertexData;
  37299. };
  37300. /**
  37301. * Creates the VertexData for a box
  37302. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37303. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37304. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37305. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37306. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37307. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37308. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37309. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37310. * * 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)
  37311. * * 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)
  37312. * @returns the VertexData of the box
  37313. */
  37314. VertexData.CreateBox = function (options) {
  37315. var normalsSource = [
  37316. new BABYLON.Vector3(0, 0, 1),
  37317. new BABYLON.Vector3(0, 0, -1),
  37318. new BABYLON.Vector3(1, 0, 0),
  37319. new BABYLON.Vector3(-1, 0, 0),
  37320. new BABYLON.Vector3(0, 1, 0),
  37321. new BABYLON.Vector3(0, -1, 0)
  37322. ];
  37323. var indices = [];
  37324. var positions = [];
  37325. var normals = [];
  37326. var uvs = [];
  37327. var width = options.width || options.size || 1;
  37328. var height = options.height || options.size || 1;
  37329. var depth = options.depth || options.size || 1;
  37330. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37331. var faceUV = options.faceUV || new Array(6);
  37332. var faceColors = options.faceColors;
  37333. var colors = [];
  37334. // default face colors and UV if undefined
  37335. for (var f = 0; f < 6; f++) {
  37336. if (faceUV[f] === undefined) {
  37337. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37338. }
  37339. if (faceColors && faceColors[f] === undefined) {
  37340. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37341. }
  37342. }
  37343. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37344. // Create each face in turn.
  37345. for (var index = 0; index < normalsSource.length; index++) {
  37346. var normal = normalsSource[index];
  37347. // Get two vectors perpendicular to the face normal and to each other.
  37348. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37349. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37350. // Six indices (two triangles) per face.
  37351. var verticesLength = positions.length / 3;
  37352. indices.push(verticesLength);
  37353. indices.push(verticesLength + 1);
  37354. indices.push(verticesLength + 2);
  37355. indices.push(verticesLength);
  37356. indices.push(verticesLength + 2);
  37357. indices.push(verticesLength + 3);
  37358. // Four vertices per face.
  37359. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37360. positions.push(vertex.x, vertex.y, vertex.z);
  37361. normals.push(normal.x, normal.y, normal.z);
  37362. uvs.push(faceUV[index].z, faceUV[index].w);
  37363. if (faceColors) {
  37364. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37365. }
  37366. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37367. positions.push(vertex.x, vertex.y, vertex.z);
  37368. normals.push(normal.x, normal.y, normal.z);
  37369. uvs.push(faceUV[index].x, faceUV[index].w);
  37370. if (faceColors) {
  37371. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37372. }
  37373. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37374. positions.push(vertex.x, vertex.y, vertex.z);
  37375. normals.push(normal.x, normal.y, normal.z);
  37376. uvs.push(faceUV[index].x, faceUV[index].y);
  37377. if (faceColors) {
  37378. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37379. }
  37380. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37381. positions.push(vertex.x, vertex.y, vertex.z);
  37382. normals.push(normal.x, normal.y, normal.z);
  37383. uvs.push(faceUV[index].z, faceUV[index].y);
  37384. if (faceColors) {
  37385. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37386. }
  37387. }
  37388. // sides
  37389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37390. // Result
  37391. var vertexData = new VertexData();
  37392. vertexData.indices = indices;
  37393. vertexData.positions = positions;
  37394. vertexData.normals = normals;
  37395. vertexData.uvs = uvs;
  37396. if (faceColors) {
  37397. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37398. vertexData.colors = totalColors;
  37399. }
  37400. return vertexData;
  37401. };
  37402. /**
  37403. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37404. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37405. * * segments sets the number of horizontal strips optional, default 32
  37406. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37407. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37408. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37409. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37410. * * 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
  37411. * * 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
  37412. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37413. * * 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)
  37414. * * 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)
  37415. * @returns the VertexData of the ellipsoid
  37416. */
  37417. VertexData.CreateSphere = function (options) {
  37418. var segments = options.segments || 32;
  37419. var diameterX = options.diameterX || options.diameter || 1;
  37420. var diameterY = options.diameterY || options.diameter || 1;
  37421. var diameterZ = options.diameterZ || options.diameter || 1;
  37422. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37423. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37424. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37425. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37426. var totalZRotationSteps = 2 + segments;
  37427. var totalYRotationSteps = 2 * totalZRotationSteps;
  37428. var indices = [];
  37429. var positions = [];
  37430. var normals = [];
  37431. var uvs = [];
  37432. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37433. var normalizedZ = zRotationStep / totalZRotationSteps;
  37434. var angleZ = normalizedZ * Math.PI * slice;
  37435. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37436. var normalizedY = yRotationStep / totalYRotationSteps;
  37437. var angleY = normalizedY * Math.PI * 2 * arc;
  37438. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37439. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37440. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37441. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37442. var vertex = complete.multiply(radius);
  37443. var normal = complete.divide(radius).normalize();
  37444. positions.push(vertex.x, vertex.y, vertex.z);
  37445. normals.push(normal.x, normal.y, normal.z);
  37446. uvs.push(normalizedY, normalizedZ);
  37447. }
  37448. if (zRotationStep > 0) {
  37449. var verticesCount = positions.length / 3;
  37450. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37451. indices.push((firstIndex));
  37452. indices.push((firstIndex + 1));
  37453. indices.push(firstIndex + totalYRotationSteps + 1);
  37454. indices.push((firstIndex + totalYRotationSteps + 1));
  37455. indices.push((firstIndex + 1));
  37456. indices.push((firstIndex + totalYRotationSteps + 2));
  37457. }
  37458. }
  37459. }
  37460. // Sides
  37461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37462. // Result
  37463. var vertexData = new VertexData();
  37464. vertexData.indices = indices;
  37465. vertexData.positions = positions;
  37466. vertexData.normals = normals;
  37467. vertexData.uvs = uvs;
  37468. return vertexData;
  37469. };
  37470. /**
  37471. * Creates the VertexData for a cylinder, cone or prism
  37472. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37473. * * height sets the height (y direction) of the cylinder, optional, default 2
  37474. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37475. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37476. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37477. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37478. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37479. * * 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
  37480. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37481. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37482. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37483. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37484. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37485. * * 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)
  37486. * * 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)
  37487. * @returns the VertexData of the cylinder, cone or prism
  37488. */
  37489. VertexData.CreateCylinder = function (options) {
  37490. var height = options.height || 2;
  37491. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37492. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37493. var tessellation = options.tessellation || 24;
  37494. var subdivisions = options.subdivisions || 1;
  37495. var hasRings = options.hasRings ? true : false;
  37496. var enclose = options.enclose ? true : false;
  37497. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37499. var faceUV = options.faceUV || new Array(3);
  37500. var faceColors = options.faceColors;
  37501. // default face colors and UV if undefined
  37502. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37503. var ringNb = (hasRings) ? subdivisions : 1;
  37504. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37505. var f;
  37506. for (f = 0; f < surfaceNb; f++) {
  37507. if (faceColors && faceColors[f] === undefined) {
  37508. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37509. }
  37510. }
  37511. for (f = 0; f < surfaceNb; f++) {
  37512. if (faceUV && faceUV[f] === undefined) {
  37513. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37514. }
  37515. }
  37516. var indices = new Array();
  37517. var positions = new Array();
  37518. var normals = new Array();
  37519. var uvs = new Array();
  37520. var colors = new Array();
  37521. var angle_step = Math.PI * 2 * arc / tessellation;
  37522. var angle;
  37523. var h;
  37524. var radius;
  37525. var tan = (diameterBottom - diameterTop) / 2 / height;
  37526. var ringVertex = BABYLON.Vector3.Zero();
  37527. var ringNormal = BABYLON.Vector3.Zero();
  37528. var ringFirstVertex = BABYLON.Vector3.Zero();
  37529. var ringFirstNormal = BABYLON.Vector3.Zero();
  37530. var quadNormal = BABYLON.Vector3.Zero();
  37531. var Y = BABYLON.Axis.Y;
  37532. // positions, normals, uvs
  37533. var i;
  37534. var j;
  37535. var r;
  37536. var ringIdx = 1;
  37537. var s = 1; // surface index
  37538. var cs = 0;
  37539. var v = 0;
  37540. for (i = 0; i <= subdivisions; i++) {
  37541. h = i / subdivisions;
  37542. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37543. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37544. for (r = 0; r < ringIdx; r++) {
  37545. if (hasRings) {
  37546. s += r;
  37547. }
  37548. if (enclose) {
  37549. s += 2 * r;
  37550. }
  37551. for (j = 0; j <= tessellation; j++) {
  37552. angle = j * angle_step;
  37553. // position
  37554. ringVertex.x = Math.cos(-angle) * radius;
  37555. ringVertex.y = -height / 2 + h * height;
  37556. ringVertex.z = Math.sin(-angle) * radius;
  37557. // normal
  37558. if (diameterTop === 0 && i === subdivisions) {
  37559. // if no top cap, reuse former normals
  37560. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37561. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37562. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37563. }
  37564. else {
  37565. ringNormal.x = ringVertex.x;
  37566. ringNormal.z = ringVertex.z;
  37567. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37568. ringNormal.normalize();
  37569. }
  37570. // keep first ring vertex values for enclose
  37571. if (j === 0) {
  37572. ringFirstVertex.copyFrom(ringVertex);
  37573. ringFirstNormal.copyFrom(ringNormal);
  37574. }
  37575. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37576. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37577. if (hasRings) {
  37578. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37579. }
  37580. else {
  37581. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37582. }
  37583. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37584. if (faceColors) {
  37585. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37586. }
  37587. }
  37588. // if enclose, add four vertices and their dedicated normals
  37589. if (arc !== 1 && enclose) {
  37590. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37591. positions.push(0, ringVertex.y, 0);
  37592. positions.push(0, ringVertex.y, 0);
  37593. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37594. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37595. quadNormal.normalize();
  37596. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37597. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37598. quadNormal.normalize();
  37599. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37600. if (hasRings) {
  37601. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37602. }
  37603. else {
  37604. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37605. }
  37606. uvs.push(faceUV[s + 1].x, v);
  37607. uvs.push(faceUV[s + 1].z, v);
  37608. if (hasRings) {
  37609. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37610. }
  37611. else {
  37612. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37613. }
  37614. uvs.push(faceUV[s + 2].x, v);
  37615. uvs.push(faceUV[s + 2].z, v);
  37616. if (faceColors) {
  37617. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37618. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37619. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37620. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37621. }
  37622. }
  37623. if (cs !== s) {
  37624. cs = s;
  37625. }
  37626. }
  37627. }
  37628. // indices
  37629. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37630. var s;
  37631. i = 0;
  37632. for (s = 0; s < subdivisions; s++) {
  37633. var i0 = 0;
  37634. var i1 = 0;
  37635. var i2 = 0;
  37636. var i3 = 0;
  37637. for (j = 0; j < tessellation; j++) {
  37638. i0 = i * (e + 1) + j;
  37639. i1 = (i + 1) * (e + 1) + j;
  37640. i2 = i * (e + 1) + (j + 1);
  37641. i3 = (i + 1) * (e + 1) + (j + 1);
  37642. indices.push(i0, i1, i2);
  37643. indices.push(i3, i2, i1);
  37644. }
  37645. if (arc !== 1 && enclose) { // if enclose, add two quads
  37646. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37647. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37648. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37649. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37650. }
  37651. i = (hasRings) ? (i + 2) : (i + 1);
  37652. }
  37653. // Caps
  37654. var createCylinderCap = function (isTop) {
  37655. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37656. if (radius === 0) {
  37657. return;
  37658. }
  37659. // Cap positions, normals & uvs
  37660. var angle;
  37661. var circleVector;
  37662. var i;
  37663. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37664. var c = null;
  37665. if (faceColors) {
  37666. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37667. }
  37668. // cap center
  37669. var vbase = positions.length / 3;
  37670. var offset = isTop ? height / 2 : -height / 2;
  37671. var center = new BABYLON.Vector3(0, offset, 0);
  37672. positions.push(center.x, center.y, center.z);
  37673. normals.push(0, isTop ? 1 : -1, 0);
  37674. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37675. if (c) {
  37676. colors.push(c.r, c.g, c.b, c.a);
  37677. }
  37678. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37679. for (i = 0; i <= tessellation; i++) {
  37680. angle = Math.PI * 2 * i * arc / tessellation;
  37681. var cos = Math.cos(-angle);
  37682. var sin = Math.sin(-angle);
  37683. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37684. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37685. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37686. normals.push(0, isTop ? 1 : -1, 0);
  37687. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37688. if (c) {
  37689. colors.push(c.r, c.g, c.b, c.a);
  37690. }
  37691. }
  37692. // Cap indices
  37693. for (i = 0; i < tessellation; i++) {
  37694. if (!isTop) {
  37695. indices.push(vbase);
  37696. indices.push(vbase + (i + 1));
  37697. indices.push(vbase + (i + 2));
  37698. }
  37699. else {
  37700. indices.push(vbase);
  37701. indices.push(vbase + (i + 2));
  37702. indices.push(vbase + (i + 1));
  37703. }
  37704. }
  37705. };
  37706. // add caps to geometry
  37707. createCylinderCap(false);
  37708. createCylinderCap(true);
  37709. // Sides
  37710. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37711. var vertexData = new VertexData();
  37712. vertexData.indices = indices;
  37713. vertexData.positions = positions;
  37714. vertexData.normals = normals;
  37715. vertexData.uvs = uvs;
  37716. if (faceColors) {
  37717. vertexData.colors = colors;
  37718. }
  37719. return vertexData;
  37720. };
  37721. /**
  37722. * Creates the VertexData for a torus
  37723. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37724. * * diameter the diameter of the torus, optional default 1
  37725. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37726. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37727. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37728. * * 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)
  37729. * * 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)
  37730. * @returns the VertexData of the torus
  37731. */
  37732. VertexData.CreateTorus = function (options) {
  37733. var indices = [];
  37734. var positions = [];
  37735. var normals = [];
  37736. var uvs = [];
  37737. var diameter = options.diameter || 1;
  37738. var thickness = options.thickness || 0.5;
  37739. var tessellation = options.tessellation || 16;
  37740. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37741. var stride = tessellation + 1;
  37742. for (var i = 0; i <= tessellation; i++) {
  37743. var u = i / tessellation;
  37744. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37745. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37746. for (var j = 0; j <= tessellation; j++) {
  37747. var v = 1 - j / tessellation;
  37748. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37749. var dx = Math.cos(innerAngle);
  37750. var dy = Math.sin(innerAngle);
  37751. // Create a vertex.
  37752. var normal = new BABYLON.Vector3(dx, dy, 0);
  37753. var position = normal.scale(thickness / 2);
  37754. var textureCoordinate = new BABYLON.Vector2(u, v);
  37755. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37756. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37757. positions.push(position.x, position.y, position.z);
  37758. normals.push(normal.x, normal.y, normal.z);
  37759. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37760. // And create indices for two triangles.
  37761. var nextI = (i + 1) % stride;
  37762. var nextJ = (j + 1) % stride;
  37763. indices.push(i * stride + j);
  37764. indices.push(i * stride + nextJ);
  37765. indices.push(nextI * stride + j);
  37766. indices.push(i * stride + nextJ);
  37767. indices.push(nextI * stride + nextJ);
  37768. indices.push(nextI * stride + j);
  37769. }
  37770. }
  37771. // Sides
  37772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37773. // Result
  37774. var vertexData = new VertexData();
  37775. vertexData.indices = indices;
  37776. vertexData.positions = positions;
  37777. vertexData.normals = normals;
  37778. vertexData.uvs = uvs;
  37779. return vertexData;
  37780. };
  37781. /**
  37782. * Creates the VertexData of the LineSystem
  37783. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37784. * - lines an array of lines, each line being an array of successive Vector3
  37785. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37786. * @returns the VertexData of the LineSystem
  37787. */
  37788. VertexData.CreateLineSystem = function (options) {
  37789. var indices = [];
  37790. var positions = [];
  37791. var lines = options.lines;
  37792. var colors = options.colors;
  37793. var vertexColors = [];
  37794. var idx = 0;
  37795. for (var l = 0; l < lines.length; l++) {
  37796. var points = lines[l];
  37797. for (var index = 0; index < points.length; index++) {
  37798. positions.push(points[index].x, points[index].y, points[index].z);
  37799. if (colors) {
  37800. var color = colors[l];
  37801. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37802. }
  37803. if (index > 0) {
  37804. indices.push(idx - 1);
  37805. indices.push(idx);
  37806. }
  37807. idx++;
  37808. }
  37809. }
  37810. var vertexData = new VertexData();
  37811. vertexData.indices = indices;
  37812. vertexData.positions = positions;
  37813. if (colors) {
  37814. vertexData.colors = vertexColors;
  37815. }
  37816. return vertexData;
  37817. };
  37818. /**
  37819. * Create the VertexData for a DashedLines
  37820. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37821. * - points an array successive Vector3
  37822. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37823. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37824. * - dashNb the intended total number of dashes, optional, default 200
  37825. * @returns the VertexData for the DashedLines
  37826. */
  37827. VertexData.CreateDashedLines = function (options) {
  37828. var dashSize = options.dashSize || 3;
  37829. var gapSize = options.gapSize || 1;
  37830. var dashNb = options.dashNb || 200;
  37831. var points = options.points;
  37832. var positions = new Array();
  37833. var indices = new Array();
  37834. var curvect = BABYLON.Vector3.Zero();
  37835. var lg = 0;
  37836. var nb = 0;
  37837. var shft = 0;
  37838. var dashshft = 0;
  37839. var curshft = 0;
  37840. var idx = 0;
  37841. var i = 0;
  37842. for (i = 0; i < points.length - 1; i++) {
  37843. points[i + 1].subtractToRef(points[i], curvect);
  37844. lg += curvect.length();
  37845. }
  37846. shft = lg / dashNb;
  37847. dashshft = dashSize * shft / (dashSize + gapSize);
  37848. for (i = 0; i < points.length - 1; i++) {
  37849. points[i + 1].subtractToRef(points[i], curvect);
  37850. nb = Math.floor(curvect.length() / shft);
  37851. curvect.normalize();
  37852. for (var j = 0; j < nb; j++) {
  37853. curshft = shft * j;
  37854. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37855. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37856. indices.push(idx, idx + 1);
  37857. idx += 2;
  37858. }
  37859. }
  37860. // Result
  37861. var vertexData = new VertexData();
  37862. vertexData.positions = positions;
  37863. vertexData.indices = indices;
  37864. return vertexData;
  37865. };
  37866. /**
  37867. * Creates the VertexData for a Ground
  37868. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37869. * - width the width (x direction) of the ground, optional, default 1
  37870. * - height the height (z direction) of the ground, optional, default 1
  37871. * - subdivisions the number of subdivisions per side, optional, default 1
  37872. * @returns the VertexData of the Ground
  37873. */
  37874. VertexData.CreateGround = function (options) {
  37875. var indices = [];
  37876. var positions = [];
  37877. var normals = [];
  37878. var uvs = [];
  37879. var row, col;
  37880. var width = options.width || 1;
  37881. var height = options.height || 1;
  37882. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37883. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37884. for (row = 0; row <= subdivisionsY; row++) {
  37885. for (col = 0; col <= subdivisionsX; col++) {
  37886. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37887. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37888. positions.push(position.x, position.y, position.z);
  37889. normals.push(normal.x, normal.y, normal.z);
  37890. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37891. }
  37892. }
  37893. for (row = 0; row < subdivisionsY; row++) {
  37894. for (col = 0; col < subdivisionsX; col++) {
  37895. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37896. indices.push(col + 1 + row * (subdivisionsX + 1));
  37897. indices.push(col + row * (subdivisionsX + 1));
  37898. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37899. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37900. indices.push(col + row * (subdivisionsX + 1));
  37901. }
  37902. }
  37903. // Result
  37904. var vertexData = new VertexData();
  37905. vertexData.indices = indices;
  37906. vertexData.positions = positions;
  37907. vertexData.normals = normals;
  37908. vertexData.uvs = uvs;
  37909. return vertexData;
  37910. };
  37911. /**
  37912. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37913. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37914. * * xmin the ground minimum X coordinate, optional, default -1
  37915. * * zmin the ground minimum Z coordinate, optional, default -1
  37916. * * xmax the ground maximum X coordinate, optional, default 1
  37917. * * zmax the ground maximum Z coordinate, optional, default 1
  37918. * * 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}
  37919. * * 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}
  37920. * @returns the VertexData of the TiledGround
  37921. */
  37922. VertexData.CreateTiledGround = function (options) {
  37923. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37924. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37925. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37926. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37927. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37928. var precision = options.precision || { w: 1, h: 1 };
  37929. var indices = new Array();
  37930. var positions = new Array();
  37931. var normals = new Array();
  37932. var uvs = new Array();
  37933. var row, col, tileRow, tileCol;
  37934. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37935. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37936. precision.w = (precision.w < 1) ? 1 : precision.w;
  37937. precision.h = (precision.h < 1) ? 1 : precision.h;
  37938. var tileSize = {
  37939. 'w': (xmax - xmin) / subdivisions.w,
  37940. 'h': (zmax - zmin) / subdivisions.h
  37941. };
  37942. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37943. // Indices
  37944. var base = positions.length / 3;
  37945. var rowLength = precision.w + 1;
  37946. for (row = 0; row < precision.h; row++) {
  37947. for (col = 0; col < precision.w; col++) {
  37948. var square = [
  37949. base + col + row * rowLength,
  37950. base + (col + 1) + row * rowLength,
  37951. base + (col + 1) + (row + 1) * rowLength,
  37952. base + col + (row + 1) * rowLength
  37953. ];
  37954. indices.push(square[1]);
  37955. indices.push(square[2]);
  37956. indices.push(square[3]);
  37957. indices.push(square[0]);
  37958. indices.push(square[1]);
  37959. indices.push(square[3]);
  37960. }
  37961. }
  37962. // Position, normals and uvs
  37963. var position = BABYLON.Vector3.Zero();
  37964. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37965. for (row = 0; row <= precision.h; row++) {
  37966. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37967. for (col = 0; col <= precision.w; col++) {
  37968. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37969. position.y = 0;
  37970. positions.push(position.x, position.y, position.z);
  37971. normals.push(normal.x, normal.y, normal.z);
  37972. uvs.push(col / precision.w, row / precision.h);
  37973. }
  37974. }
  37975. }
  37976. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37977. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37978. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37979. }
  37980. }
  37981. // Result
  37982. var vertexData = new VertexData();
  37983. vertexData.indices = indices;
  37984. vertexData.positions = positions;
  37985. vertexData.normals = normals;
  37986. vertexData.uvs = uvs;
  37987. return vertexData;
  37988. };
  37989. /**
  37990. * Creates the VertexData of the Ground designed from a heightmap
  37991. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37992. * * width the width (x direction) of the ground
  37993. * * height the height (z direction) of the ground
  37994. * * subdivisions the number of subdivisions per side
  37995. * * minHeight the minimum altitude on the ground, optional, default 0
  37996. * * maxHeight the maximum altitude on the ground, optional default 1
  37997. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37998. * * buffer the array holding the image color data
  37999. * * bufferWidth the width of image
  38000. * * bufferHeight the height of image
  38001. * @returns the VertexData of the Ground designed from a heightmap
  38002. */
  38003. VertexData.CreateGroundFromHeightMap = function (options) {
  38004. var indices = [];
  38005. var positions = [];
  38006. var normals = [];
  38007. var uvs = [];
  38008. var row, col;
  38009. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38010. // Vertices
  38011. for (row = 0; row <= options.subdivisions; row++) {
  38012. for (col = 0; col <= options.subdivisions; col++) {
  38013. 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));
  38014. // Compute height
  38015. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38016. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38017. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38018. var r = options.buffer[pos] / 255.0;
  38019. var g = options.buffer[pos + 1] / 255.0;
  38020. var b = options.buffer[pos + 2] / 255.0;
  38021. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38022. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38023. // Add vertex
  38024. positions.push(position.x, position.y, position.z);
  38025. normals.push(0, 0, 0);
  38026. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38027. }
  38028. }
  38029. // Indices
  38030. for (row = 0; row < options.subdivisions; row++) {
  38031. for (col = 0; col < options.subdivisions; col++) {
  38032. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38033. indices.push(col + 1 + row * (options.subdivisions + 1));
  38034. indices.push(col + row * (options.subdivisions + 1));
  38035. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38036. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38037. indices.push(col + row * (options.subdivisions + 1));
  38038. }
  38039. }
  38040. // Normals
  38041. VertexData.ComputeNormals(positions, indices, normals);
  38042. // Result
  38043. var vertexData = new VertexData();
  38044. vertexData.indices = indices;
  38045. vertexData.positions = positions;
  38046. vertexData.normals = normals;
  38047. vertexData.uvs = uvs;
  38048. return vertexData;
  38049. };
  38050. /**
  38051. * Creates the VertexData for a Plane
  38052. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38053. * * size sets the width and height of the plane to the value of size, optional default 1
  38054. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38055. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38056. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38057. * * 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)
  38058. * * 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)
  38059. * @returns the VertexData of the box
  38060. */
  38061. VertexData.CreatePlane = function (options) {
  38062. var indices = [];
  38063. var positions = [];
  38064. var normals = [];
  38065. var uvs = [];
  38066. var width = options.width || options.size || 1;
  38067. var height = options.height || options.size || 1;
  38068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38069. // Vertices
  38070. var halfWidth = width / 2.0;
  38071. var halfHeight = height / 2.0;
  38072. positions.push(-halfWidth, -halfHeight, 0);
  38073. normals.push(0, 0, -1.0);
  38074. uvs.push(0.0, 0.0);
  38075. positions.push(halfWidth, -halfHeight, 0);
  38076. normals.push(0, 0, -1.0);
  38077. uvs.push(1.0, 0.0);
  38078. positions.push(halfWidth, halfHeight, 0);
  38079. normals.push(0, 0, -1.0);
  38080. uvs.push(1.0, 1.0);
  38081. positions.push(-halfWidth, halfHeight, 0);
  38082. normals.push(0, 0, -1.0);
  38083. uvs.push(0.0, 1.0);
  38084. // Indices
  38085. indices.push(0);
  38086. indices.push(1);
  38087. indices.push(2);
  38088. indices.push(0);
  38089. indices.push(2);
  38090. indices.push(3);
  38091. // Sides
  38092. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38093. // Result
  38094. var vertexData = new VertexData();
  38095. vertexData.indices = indices;
  38096. vertexData.positions = positions;
  38097. vertexData.normals = normals;
  38098. vertexData.uvs = uvs;
  38099. return vertexData;
  38100. };
  38101. /**
  38102. * Creates the VertexData of the Disc or regular Polygon
  38103. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38104. * * radius the radius of the disc, optional default 0.5
  38105. * * tessellation the number of polygon sides, optional, default 64
  38106. * * 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
  38107. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38108. * * 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)
  38109. * * 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)
  38110. * @returns the VertexData of the box
  38111. */
  38112. VertexData.CreateDisc = function (options) {
  38113. var positions = new Array();
  38114. var indices = new Array();
  38115. var normals = new Array();
  38116. var uvs = new Array();
  38117. var radius = options.radius || 0.5;
  38118. var tessellation = options.tessellation || 64;
  38119. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38120. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38121. // positions and uvs
  38122. positions.push(0, 0, 0); // disc center first
  38123. uvs.push(0.5, 0.5);
  38124. var theta = Math.PI * 2 * arc;
  38125. var step = theta / tessellation;
  38126. for (var a = 0; a < theta; a += step) {
  38127. var x = Math.cos(a);
  38128. var y = Math.sin(a);
  38129. var u = (x + 1) / 2;
  38130. var v = (1 - y) / 2;
  38131. positions.push(radius * x, radius * y, 0);
  38132. uvs.push(u, v);
  38133. }
  38134. if (arc === 1) {
  38135. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38136. uvs.push(uvs[2], uvs[3]);
  38137. }
  38138. //indices
  38139. var vertexNb = positions.length / 3;
  38140. for (var i = 1; i < vertexNb - 1; i++) {
  38141. indices.push(i + 1, 0, i);
  38142. }
  38143. // result
  38144. VertexData.ComputeNormals(positions, indices, normals);
  38145. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38146. var vertexData = new VertexData();
  38147. vertexData.indices = indices;
  38148. vertexData.positions = positions;
  38149. vertexData.normals = normals;
  38150. vertexData.uvs = uvs;
  38151. return vertexData;
  38152. };
  38153. /**
  38154. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38155. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38156. * @param polygon a mesh built from polygonTriangulation.build()
  38157. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38158. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38159. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38160. * @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)
  38161. * @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)
  38162. * @returns the VertexData of the Polygon
  38163. */
  38164. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38165. var faceUV = fUV || new Array(3);
  38166. var faceColors = fColors;
  38167. var colors = [];
  38168. // default face colors and UV if undefined
  38169. for (var f = 0; f < 3; f++) {
  38170. if (faceUV[f] === undefined) {
  38171. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38172. }
  38173. if (faceColors && faceColors[f] === undefined) {
  38174. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38175. }
  38176. }
  38177. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38178. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38179. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38180. var indices = polygon.getIndices();
  38181. // set face colours and textures
  38182. var idx = 0;
  38183. var face = 0;
  38184. for (var index = 0; index < normals.length; index += 3) {
  38185. //Edge Face no. 1
  38186. if (Math.abs(normals[index + 1]) < 0.001) {
  38187. face = 1;
  38188. }
  38189. //Top Face no. 0
  38190. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38191. face = 0;
  38192. }
  38193. //Bottom Face no. 2
  38194. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38195. face = 2;
  38196. }
  38197. idx = index / 3;
  38198. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38199. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38200. if (faceColors) {
  38201. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38202. }
  38203. }
  38204. // sides
  38205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38206. // Result
  38207. var vertexData = new VertexData();
  38208. vertexData.indices = indices;
  38209. vertexData.positions = positions;
  38210. vertexData.normals = normals;
  38211. vertexData.uvs = uvs;
  38212. if (faceColors) {
  38213. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38214. vertexData.colors = totalColors;
  38215. }
  38216. return vertexData;
  38217. };
  38218. /**
  38219. * Creates the VertexData of the IcoSphere
  38220. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38221. * * radius the radius of the IcoSphere, optional default 1
  38222. * * radiusX allows stretching in the x direction, optional, default radius
  38223. * * radiusY allows stretching in the y direction, optional, default radius
  38224. * * radiusZ allows stretching in the z direction, optional, default radius
  38225. * * flat when true creates a flat shaded mesh, optional, default true
  38226. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38227. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38228. * * 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)
  38229. * * 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)
  38230. * @returns the VertexData of the IcoSphere
  38231. */
  38232. VertexData.CreateIcoSphere = function (options) {
  38233. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38234. var radius = options.radius || 1;
  38235. var flat = (options.flat === undefined) ? true : options.flat;
  38236. var subdivisions = options.subdivisions || 4;
  38237. var radiusX = options.radiusX || radius;
  38238. var radiusY = options.radiusY || radius;
  38239. var radiusZ = options.radiusZ || radius;
  38240. var t = (1 + Math.sqrt(5)) / 2;
  38241. // 12 vertex x,y,z
  38242. var ico_vertices = [
  38243. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38244. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38245. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38246. ];
  38247. // index of 3 vertex makes a face of icopshere
  38248. var ico_indices = [
  38249. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38250. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38251. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38252. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38253. ];
  38254. // vertex for uv have aliased position, not for UV
  38255. var vertices_unalias_id = [
  38256. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38257. // vertex alias
  38258. 0,
  38259. 2,
  38260. 3,
  38261. 3,
  38262. 3,
  38263. 4,
  38264. 7,
  38265. 8,
  38266. 9,
  38267. 9,
  38268. 10,
  38269. 11 // 23: B + 12
  38270. ];
  38271. // uv as integer step (not pixels !)
  38272. var ico_vertexuv = [
  38273. 5, 1, 3, 1, 6, 4, 0, 0,
  38274. 5, 3, 4, 2, 2, 2, 4, 0,
  38275. 2, 0, 1, 1, 6, 0, 6, 2,
  38276. // vertex alias (for same vertex on different faces)
  38277. 0, 4,
  38278. 3, 3,
  38279. 4, 4,
  38280. 3, 1,
  38281. 4, 2,
  38282. 4, 4,
  38283. 0, 2,
  38284. 1, 1,
  38285. 2, 2,
  38286. 3, 3,
  38287. 1, 3,
  38288. 2, 4 // 23: B + 12
  38289. ];
  38290. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38291. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38292. // First island of uv mapping
  38293. // v = 4h 3+ 2
  38294. // v = 3h 9+ 4
  38295. // v = 2h 9+ 5 B
  38296. // v = 1h 9 1 0
  38297. // v = 0h 3 8 7 A
  38298. // u = 0 1 2 3 4 5 6 *a
  38299. // Second island of uv mapping
  38300. // v = 4h 0+ B+ 4+
  38301. // v = 3h A+ 2+
  38302. // v = 2h 7+ 6 3+
  38303. // v = 1h 8+ 3+
  38304. // v = 0h
  38305. // u = 0 1 2 3 4 5 6 *a
  38306. // Face layout on texture UV mapping
  38307. // ============
  38308. // \ 4 /\ 16 / ======
  38309. // \ / \ / /\ 11 /
  38310. // \/ 7 \/ / \ /
  38311. // ======= / 10 \/
  38312. // /\ 17 /\ =======
  38313. // / \ / \ \ 15 /\
  38314. // / 8 \/ 12 \ \ / \
  38315. // ============ \/ 6 \
  38316. // \ 18 /\ ============
  38317. // \ / \ \ 5 /\ 0 /
  38318. // \/ 13 \ \ / \ /
  38319. // ======= \/ 1 \/
  38320. // =============
  38321. // /\ 19 /\ 2 /\
  38322. // / \ / \ / \
  38323. // / 14 \/ 9 \/ 3 \
  38324. // ===================
  38325. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38326. var ustep = 138 / 1024;
  38327. var vstep = 239 / 1024;
  38328. var uoffset = 60 / 1024;
  38329. var voffset = 26 / 1024;
  38330. // Second island should have margin, not to touch the first island
  38331. // avoid any borderline artefact in pixel rounding
  38332. var island_u_offset = -40 / 1024;
  38333. var island_v_offset = +20 / 1024;
  38334. // face is either island 0 or 1 :
  38335. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38336. var island = [
  38337. 0, 0, 0, 0, 1,
  38338. 0, 0, 1, 1, 0,
  38339. 0, 0, 1, 1, 0,
  38340. 0, 1, 1, 1, 0 // 15 - 19
  38341. ];
  38342. var indices = new Array();
  38343. var positions = new Array();
  38344. var normals = new Array();
  38345. var uvs = new Array();
  38346. var current_indice = 0;
  38347. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38348. var face_vertex_pos = new Array(3);
  38349. var face_vertex_uv = new Array(3);
  38350. var v012;
  38351. for (v012 = 0; v012 < 3; v012++) {
  38352. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38353. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38354. }
  38355. // create all with normals
  38356. for (var face = 0; face < 20; face++) {
  38357. // 3 vertex per face
  38358. for (v012 = 0; v012 < 3; v012++) {
  38359. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38360. var v_id = ico_indices[3 * face + v012];
  38361. // vertex have 3D position (x,y,z)
  38362. 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]);
  38363. // Normalize to get normal, then scale to radius
  38364. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38365. // uv Coordinates from vertex ID
  38366. 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);
  38367. }
  38368. // Subdivide the face (interpolate pos, norm, uv)
  38369. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38370. // - norm is linear interpolation of vertex corner normal
  38371. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38372. // - uv is linear interpolation
  38373. //
  38374. // Topology is as below for sub-divide by 2
  38375. // vertex shown as v0,v1,v2
  38376. // interp index is i1 to progress in range [v0,v1[
  38377. // interp index is i2 to progress in range [v0,v2[
  38378. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38379. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38380. //
  38381. //
  38382. // i2 v2
  38383. // ^ ^
  38384. // / / \
  38385. // / / \
  38386. // / / \
  38387. // / / (0,1) \
  38388. // / #---------\
  38389. // / / \ (0,0)'/ \
  38390. // / / \ / \
  38391. // / / \ / \
  38392. // / / (0,0) \ / (1,0) \
  38393. // / #---------#---------\
  38394. // v0 v1
  38395. //
  38396. // --------------------> i1
  38397. //
  38398. // interp of (i1,i2):
  38399. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38400. // along i1 : lerp(x0,x1, i1/(S-i2))
  38401. //
  38402. // centroid of triangle is needed to get help normal computation
  38403. // (c1,c2) are used for centroid location
  38404. var interp_vertex = function (i1, i2, c1, c2) {
  38405. // vertex is interpolated from
  38406. // - face_vertex_pos[0..2]
  38407. // - face_vertex_uv[0..2]
  38408. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38409. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38410. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38411. pos_interp.normalize();
  38412. var vertex_normal;
  38413. if (flat) {
  38414. // in flat mode, recalculate normal as face centroid normal
  38415. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38416. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38417. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38418. }
  38419. else {
  38420. // in smooth mode, recalculate normal from each single vertex position
  38421. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38422. }
  38423. // Vertex normal need correction due to X,Y,Z radius scaling
  38424. vertex_normal.x /= radiusX;
  38425. vertex_normal.y /= radiusY;
  38426. vertex_normal.z /= radiusZ;
  38427. vertex_normal.normalize();
  38428. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38429. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38430. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38431. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38432. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38433. uvs.push(uv_interp.x, uv_interp.y);
  38434. // push each vertex has member of a face
  38435. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38436. indices.push(current_indice);
  38437. current_indice++;
  38438. };
  38439. for (var i2 = 0; i2 < subdivisions; i2++) {
  38440. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38441. // face : (i1,i2) for /\ :
  38442. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38443. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38444. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38445. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38446. if (i1 + i2 + 1 < subdivisions) {
  38447. // face : (i1,i2)' for \/ :
  38448. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38449. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38450. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38451. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38452. }
  38453. }
  38454. }
  38455. }
  38456. // Sides
  38457. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38458. // Result
  38459. var vertexData = new VertexData();
  38460. vertexData.indices = indices;
  38461. vertexData.positions = positions;
  38462. vertexData.normals = normals;
  38463. vertexData.uvs = uvs;
  38464. return vertexData;
  38465. };
  38466. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38467. /**
  38468. * Creates the VertexData for a Polyhedron
  38469. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38470. * * type provided types are:
  38471. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38472. * * 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)
  38473. * * size the size of the IcoSphere, optional default 1
  38474. * * sizeX allows stretching in the x direction, optional, default size
  38475. * * sizeY allows stretching in the y direction, optional, default size
  38476. * * sizeZ allows stretching in the z direction, optional, default size
  38477. * * 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
  38478. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38479. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38480. * * flat when true creates a flat shaded mesh, optional, default true
  38481. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38482. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38483. * * 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)
  38484. * * 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)
  38485. * @returns the VertexData of the Polyhedron
  38486. */
  38487. VertexData.CreatePolyhedron = function (options) {
  38488. // provided polyhedron types :
  38489. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38490. // 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)
  38491. var polyhedra = [];
  38492. 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]] };
  38493. 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]] };
  38494. polyhedra[2] = {
  38495. 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]],
  38496. 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]]
  38497. };
  38498. polyhedra[3] = {
  38499. 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]],
  38500. 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]]
  38501. };
  38502. polyhedra[4] = {
  38503. 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]],
  38504. 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]]
  38505. };
  38506. 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]] };
  38507. 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]] };
  38508. 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]] };
  38509. 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]] };
  38510. 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]] };
  38511. 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]] };
  38512. 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]] };
  38513. 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]] };
  38514. 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]] };
  38515. polyhedra[14] = {
  38516. 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]],
  38517. 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]]
  38518. };
  38519. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38520. var size = options.size;
  38521. var sizeX = options.sizeX || size || 1;
  38522. var sizeY = options.sizeY || size || 1;
  38523. var sizeZ = options.sizeZ || size || 1;
  38524. var data = options.custom || polyhedra[type];
  38525. var nbfaces = data.face.length;
  38526. var faceUV = options.faceUV || new Array(nbfaces);
  38527. var faceColors = options.faceColors;
  38528. var flat = (options.flat === undefined) ? true : options.flat;
  38529. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38530. var positions = new Array();
  38531. var indices = new Array();
  38532. var normals = new Array();
  38533. var uvs = new Array();
  38534. var colors = new Array();
  38535. var index = 0;
  38536. var faceIdx = 0; // face cursor in the array "indexes"
  38537. var indexes = new Array();
  38538. var i = 0;
  38539. var f = 0;
  38540. var u, v, ang, x, y, tmp;
  38541. // default face colors and UV if undefined
  38542. if (flat) {
  38543. for (f = 0; f < nbfaces; f++) {
  38544. if (faceColors && faceColors[f] === undefined) {
  38545. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38546. }
  38547. if (faceUV && faceUV[f] === undefined) {
  38548. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38549. }
  38550. }
  38551. }
  38552. if (!flat) {
  38553. for (i = 0; i < data.vertex.length; i++) {
  38554. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38555. uvs.push(0, 0);
  38556. }
  38557. for (f = 0; f < nbfaces; f++) {
  38558. for (i = 0; i < data.face[f].length - 2; i++) {
  38559. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38560. }
  38561. }
  38562. }
  38563. else {
  38564. for (f = 0; f < nbfaces; f++) {
  38565. var fl = data.face[f].length; // number of vertices of the current face
  38566. ang = 2 * Math.PI / fl;
  38567. x = 0.5 * Math.tan(ang / 2);
  38568. y = 0.5;
  38569. // positions, uvs, colors
  38570. for (i = 0; i < fl; i++) {
  38571. // positions
  38572. 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);
  38573. indexes.push(index);
  38574. index++;
  38575. // uvs
  38576. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38577. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38578. uvs.push(u, v);
  38579. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38580. y = x * Math.sin(ang) + y * Math.cos(ang);
  38581. x = tmp;
  38582. // colors
  38583. if (faceColors) {
  38584. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38585. }
  38586. }
  38587. // indices from indexes
  38588. for (i = 0; i < fl - 2; i++) {
  38589. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38590. }
  38591. faceIdx += fl;
  38592. }
  38593. }
  38594. VertexData.ComputeNormals(positions, indices, normals);
  38595. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38596. var vertexData = new VertexData();
  38597. vertexData.positions = positions;
  38598. vertexData.indices = indices;
  38599. vertexData.normals = normals;
  38600. vertexData.uvs = uvs;
  38601. if (faceColors && flat) {
  38602. vertexData.colors = colors;
  38603. }
  38604. return vertexData;
  38605. };
  38606. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38607. /**
  38608. * Creates the VertexData for a TorusKnot
  38609. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38610. * * radius the radius of the torus knot, optional, default 2
  38611. * * tube the thickness of the tube, optional, default 0.5
  38612. * * radialSegments the number of sides on each tube segments, optional, default 32
  38613. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38614. * * p the number of windings around the z axis, optional, default 2
  38615. * * q the number of windings around the x axis, optional, default 3
  38616. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38617. * * 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)
  38618. * * 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)
  38619. * @returns the VertexData of the Torus Knot
  38620. */
  38621. VertexData.CreateTorusKnot = function (options) {
  38622. var indices = new Array();
  38623. var positions = new Array();
  38624. var normals = new Array();
  38625. var uvs = new Array();
  38626. var radius = options.radius || 2;
  38627. var tube = options.tube || 0.5;
  38628. var radialSegments = options.radialSegments || 32;
  38629. var tubularSegments = options.tubularSegments || 32;
  38630. var p = options.p || 2;
  38631. var q = options.q || 3;
  38632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38633. // Helper
  38634. var getPos = function (angle) {
  38635. var cu = Math.cos(angle);
  38636. var su = Math.sin(angle);
  38637. var quOverP = q / p * angle;
  38638. var cs = Math.cos(quOverP);
  38639. var tx = radius * (2 + cs) * 0.5 * cu;
  38640. var ty = radius * (2 + cs) * su * 0.5;
  38641. var tz = radius * Math.sin(quOverP) * 0.5;
  38642. return new BABYLON.Vector3(tx, ty, tz);
  38643. };
  38644. // Vertices
  38645. var i;
  38646. var j;
  38647. for (i = 0; i <= radialSegments; i++) {
  38648. var modI = i % radialSegments;
  38649. var u = modI / radialSegments * 2 * p * Math.PI;
  38650. var p1 = getPos(u);
  38651. var p2 = getPos(u + 0.01);
  38652. var tang = p2.subtract(p1);
  38653. var n = p2.add(p1);
  38654. var bitan = BABYLON.Vector3.Cross(tang, n);
  38655. n = BABYLON.Vector3.Cross(bitan, tang);
  38656. bitan.normalize();
  38657. n.normalize();
  38658. for (j = 0; j < tubularSegments; j++) {
  38659. var modJ = j % tubularSegments;
  38660. var v = modJ / tubularSegments * 2 * Math.PI;
  38661. var cx = -tube * Math.cos(v);
  38662. var cy = tube * Math.sin(v);
  38663. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38664. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38665. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38666. uvs.push(i / radialSegments);
  38667. uvs.push(j / tubularSegments);
  38668. }
  38669. }
  38670. for (i = 0; i < radialSegments; i++) {
  38671. for (j = 0; j < tubularSegments; j++) {
  38672. var jNext = (j + 1) % tubularSegments;
  38673. var a = i * tubularSegments + j;
  38674. var b = (i + 1) * tubularSegments + j;
  38675. var c = (i + 1) * tubularSegments + jNext;
  38676. var d = i * tubularSegments + jNext;
  38677. indices.push(d);
  38678. indices.push(b);
  38679. indices.push(a);
  38680. indices.push(d);
  38681. indices.push(c);
  38682. indices.push(b);
  38683. }
  38684. }
  38685. // Normals
  38686. VertexData.ComputeNormals(positions, indices, normals);
  38687. // Sides
  38688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38689. // Result
  38690. var vertexData = new VertexData();
  38691. vertexData.indices = indices;
  38692. vertexData.positions = positions;
  38693. vertexData.normals = normals;
  38694. vertexData.uvs = uvs;
  38695. return vertexData;
  38696. };
  38697. // Tools
  38698. /**
  38699. * Compute normals for given positions and indices
  38700. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38701. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38702. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38703. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38704. * * facetNormals : optional array of facet normals (vector3)
  38705. * * facetPositions : optional array of facet positions (vector3)
  38706. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38707. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38708. * * bInfo : optional bounding info, required for facetPartitioning computation
  38709. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38710. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38711. * * useRightHandedSystem: optional boolean to for right handed system computation
  38712. * * depthSort : optional boolean to enable the facet depth sort computation
  38713. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38714. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38715. */
  38716. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38717. // temporary scalar variables
  38718. var index = 0; // facet index
  38719. var p1p2x = 0.0; // p1p2 vector x coordinate
  38720. var p1p2y = 0.0; // p1p2 vector y coordinate
  38721. var p1p2z = 0.0; // p1p2 vector z coordinate
  38722. var p3p2x = 0.0; // p3p2 vector x coordinate
  38723. var p3p2y = 0.0; // p3p2 vector y coordinate
  38724. var p3p2z = 0.0; // p3p2 vector z coordinate
  38725. var faceNormalx = 0.0; // facet normal x coordinate
  38726. var faceNormaly = 0.0; // facet normal y coordinate
  38727. var faceNormalz = 0.0; // facet normal z coordinate
  38728. var length = 0.0; // facet normal length before normalization
  38729. var v1x = 0; // vector1 x index in the positions array
  38730. var v1y = 0; // vector1 y index in the positions array
  38731. var v1z = 0; // vector1 z index in the positions array
  38732. var v2x = 0; // vector2 x index in the positions array
  38733. var v2y = 0; // vector2 y index in the positions array
  38734. var v2z = 0; // vector2 z index in the positions array
  38735. var v3x = 0; // vector3 x index in the positions array
  38736. var v3y = 0; // vector3 y index in the positions array
  38737. var v3z = 0; // vector3 z index in the positions array
  38738. var computeFacetNormals = false;
  38739. var computeFacetPositions = false;
  38740. var computeFacetPartitioning = false;
  38741. var computeDepthSort = false;
  38742. var faceNormalSign = 1;
  38743. var ratio = 0;
  38744. var distanceTo = null;
  38745. if (options) {
  38746. computeFacetNormals = (options.facetNormals) ? true : false;
  38747. computeFacetPositions = (options.facetPositions) ? true : false;
  38748. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38749. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38750. ratio = options.ratio || 0;
  38751. computeDepthSort = (options.depthSort) ? true : false;
  38752. distanceTo = (options.distanceTo);
  38753. if (computeDepthSort) {
  38754. if (distanceTo === undefined) {
  38755. distanceTo = BABYLON.Vector3.Zero();
  38756. }
  38757. var depthSortedFacets = options.depthSortedFacets;
  38758. }
  38759. }
  38760. // facetPartitioning reinit if needed
  38761. var xSubRatio = 0;
  38762. var ySubRatio = 0;
  38763. var zSubRatio = 0;
  38764. var subSq = 0;
  38765. if (computeFacetPartitioning && options && options.bbSize) {
  38766. var ox = 0; // X partitioning index for facet position
  38767. var oy = 0; // Y partinioning index for facet position
  38768. var oz = 0; // Z partinioning index for facet position
  38769. var b1x = 0; // X partitioning index for facet v1 vertex
  38770. var b1y = 0; // Y partitioning index for facet v1 vertex
  38771. var b1z = 0; // z partitioning index for facet v1 vertex
  38772. var b2x = 0; // X partitioning index for facet v2 vertex
  38773. var b2y = 0; // Y partitioning index for facet v2 vertex
  38774. var b2z = 0; // Z partitioning index for facet v2 vertex
  38775. var b3x = 0; // X partitioning index for facet v3 vertex
  38776. var b3y = 0; // Y partitioning index for facet v3 vertex
  38777. var b3z = 0; // Z partitioning index for facet v3 vertex
  38778. var block_idx_o = 0; // facet barycenter block index
  38779. var block_idx_v1 = 0; // v1 vertex block index
  38780. var block_idx_v2 = 0; // v2 vertex block index
  38781. var block_idx_v3 = 0; // v3 vertex block index
  38782. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38783. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38784. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38785. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38786. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38787. subSq = options.subDiv.max * options.subDiv.max;
  38788. options.facetPartitioning.length = 0;
  38789. }
  38790. // reset the normals
  38791. for (index = 0; index < positions.length; index++) {
  38792. normals[index] = 0.0;
  38793. }
  38794. // Loop : 1 indice triplet = 1 facet
  38795. var nbFaces = (indices.length / 3) | 0;
  38796. for (index = 0; index < nbFaces; index++) {
  38797. // get the indexes of the coordinates of each vertex of the facet
  38798. v1x = indices[index * 3] * 3;
  38799. v1y = v1x + 1;
  38800. v1z = v1x + 2;
  38801. v2x = indices[index * 3 + 1] * 3;
  38802. v2y = v2x + 1;
  38803. v2z = v2x + 2;
  38804. v3x = indices[index * 3 + 2] * 3;
  38805. v3y = v3x + 1;
  38806. v3z = v3x + 2;
  38807. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38808. p1p2y = positions[v1y] - positions[v2y];
  38809. p1p2z = positions[v1z] - positions[v2z];
  38810. p3p2x = positions[v3x] - positions[v2x];
  38811. p3p2y = positions[v3y] - positions[v2y];
  38812. p3p2z = positions[v3z] - positions[v2z];
  38813. // compute the face normal with the cross product
  38814. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38815. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38816. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38817. // normalize this normal and store it in the array facetData
  38818. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38819. length = (length === 0) ? 1.0 : length;
  38820. faceNormalx /= length;
  38821. faceNormaly /= length;
  38822. faceNormalz /= length;
  38823. if (computeFacetNormals && options) {
  38824. options.facetNormals[index].x = faceNormalx;
  38825. options.facetNormals[index].y = faceNormaly;
  38826. options.facetNormals[index].z = faceNormalz;
  38827. }
  38828. if (computeFacetPositions && options) {
  38829. // compute and the facet barycenter coordinates in the array facetPositions
  38830. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38831. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38832. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38833. }
  38834. if (computeFacetPartitioning && options) {
  38835. // store the facet indexes in arrays in the main facetPartitioning array :
  38836. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38837. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38838. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38839. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38840. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38841. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38842. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38843. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38844. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38845. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38846. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38847. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38848. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38849. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38850. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38851. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38852. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38853. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38854. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38855. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38856. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38857. // push each facet index in each block containing the vertex
  38858. options.facetPartitioning[block_idx_v1].push(index);
  38859. if (block_idx_v2 != block_idx_v1) {
  38860. options.facetPartitioning[block_idx_v2].push(index);
  38861. }
  38862. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38863. options.facetPartitioning[block_idx_v3].push(index);
  38864. }
  38865. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38866. options.facetPartitioning[block_idx_o].push(index);
  38867. }
  38868. }
  38869. if (computeDepthSort && options && options.facetPositions) {
  38870. var dsf = depthSortedFacets[index];
  38871. dsf.ind = index * 3;
  38872. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38873. }
  38874. // compute the normals anyway
  38875. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38876. normals[v1y] += faceNormaly;
  38877. normals[v1z] += faceNormalz;
  38878. normals[v2x] += faceNormalx;
  38879. normals[v2y] += faceNormaly;
  38880. normals[v2z] += faceNormalz;
  38881. normals[v3x] += faceNormalx;
  38882. normals[v3y] += faceNormaly;
  38883. normals[v3z] += faceNormalz;
  38884. }
  38885. // last normalization of each normal
  38886. for (index = 0; index < normals.length / 3; index++) {
  38887. faceNormalx = normals[index * 3];
  38888. faceNormaly = normals[index * 3 + 1];
  38889. faceNormalz = normals[index * 3 + 2];
  38890. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38891. length = (length === 0) ? 1.0 : length;
  38892. faceNormalx /= length;
  38893. faceNormaly /= length;
  38894. faceNormalz /= length;
  38895. normals[index * 3] = faceNormalx;
  38896. normals[index * 3 + 1] = faceNormaly;
  38897. normals[index * 3 + 2] = faceNormalz;
  38898. }
  38899. };
  38900. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38901. var li = indices.length;
  38902. var ln = normals.length;
  38903. var i;
  38904. var n;
  38905. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38906. switch (sideOrientation) {
  38907. case BABYLON.Mesh.FRONTSIDE:
  38908. // nothing changed
  38909. break;
  38910. case BABYLON.Mesh.BACKSIDE:
  38911. var tmp;
  38912. // indices
  38913. for (i = 0; i < li; i += 3) {
  38914. tmp = indices[i];
  38915. indices[i] = indices[i + 2];
  38916. indices[i + 2] = tmp;
  38917. }
  38918. // normals
  38919. for (n = 0; n < ln; n++) {
  38920. normals[n] = -normals[n];
  38921. }
  38922. break;
  38923. case BABYLON.Mesh.DOUBLESIDE:
  38924. // positions
  38925. var lp = positions.length;
  38926. var l = lp / 3;
  38927. for (var p = 0; p < lp; p++) {
  38928. positions[lp + p] = positions[p];
  38929. }
  38930. // indices
  38931. for (i = 0; i < li; i += 3) {
  38932. indices[i + li] = indices[i + 2] + l;
  38933. indices[i + 1 + li] = indices[i + 1] + l;
  38934. indices[i + 2 + li] = indices[i] + l;
  38935. }
  38936. // normals
  38937. for (n = 0; n < ln; n++) {
  38938. normals[ln + n] = -normals[n];
  38939. }
  38940. // uvs
  38941. var lu = uvs.length;
  38942. var u = 0;
  38943. for (u = 0; u < lu; u++) {
  38944. uvs[u + lu] = uvs[u];
  38945. }
  38946. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38947. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38948. u = 0;
  38949. for (i = 0; i < lu / 2; i++) {
  38950. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38951. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38952. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38953. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38954. u += 2;
  38955. }
  38956. break;
  38957. }
  38958. };
  38959. /**
  38960. * Applies VertexData created from the imported parameters to the geometry
  38961. * @param parsedVertexData the parsed data from an imported file
  38962. * @param geometry the geometry to apply the VertexData to
  38963. */
  38964. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38965. var vertexData = new VertexData();
  38966. // positions
  38967. var positions = parsedVertexData.positions;
  38968. if (positions) {
  38969. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38970. }
  38971. // normals
  38972. var normals = parsedVertexData.normals;
  38973. if (normals) {
  38974. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38975. }
  38976. // tangents
  38977. var tangents = parsedVertexData.tangents;
  38978. if (tangents) {
  38979. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38980. }
  38981. // uvs
  38982. var uvs = parsedVertexData.uvs;
  38983. if (uvs) {
  38984. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38985. }
  38986. // uv2s
  38987. var uv2s = parsedVertexData.uv2s;
  38988. if (uv2s) {
  38989. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38990. }
  38991. // uv3s
  38992. var uv3s = parsedVertexData.uv3s;
  38993. if (uv3s) {
  38994. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38995. }
  38996. // uv4s
  38997. var uv4s = parsedVertexData.uv4s;
  38998. if (uv4s) {
  38999. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39000. }
  39001. // uv5s
  39002. var uv5s = parsedVertexData.uv5s;
  39003. if (uv5s) {
  39004. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39005. }
  39006. // uv6s
  39007. var uv6s = parsedVertexData.uv6s;
  39008. if (uv6s) {
  39009. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39010. }
  39011. // colors
  39012. var colors = parsedVertexData.colors;
  39013. if (colors) {
  39014. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39015. }
  39016. // matricesIndices
  39017. var matricesIndices = parsedVertexData.matricesIndices;
  39018. if (matricesIndices) {
  39019. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39020. }
  39021. // matricesWeights
  39022. var matricesWeights = parsedVertexData.matricesWeights;
  39023. if (matricesWeights) {
  39024. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39025. }
  39026. // indices
  39027. var indices = parsedVertexData.indices;
  39028. if (indices) {
  39029. vertexData.indices = indices;
  39030. }
  39031. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39032. };
  39033. return VertexData;
  39034. }());
  39035. BABYLON.VertexData = VertexData;
  39036. })(BABYLON || (BABYLON = {}));
  39037. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39038. var BABYLON;
  39039. (function (BABYLON) {
  39040. /**
  39041. * Class used to store geometry data (vertex buffers + index buffer)
  39042. */
  39043. var Geometry = /** @class */ (function () {
  39044. /**
  39045. * Creates a new geometry
  39046. * @param id defines the unique ID
  39047. * @param scene defines the hosting scene
  39048. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39049. * @param updatable defines if geometry must be updatable (false by default)
  39050. * @param mesh defines the mesh that will be associated with the geometry
  39051. */
  39052. function Geometry(id, scene, vertexData, updatable, mesh) {
  39053. if (updatable === void 0) { updatable = false; }
  39054. if (mesh === void 0) { mesh = null; }
  39055. /**
  39056. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39057. */
  39058. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39059. this._totalVertices = 0;
  39060. this._isDisposed = false;
  39061. this._indexBufferIsUpdatable = false;
  39062. this.id = id;
  39063. this._engine = scene.getEngine();
  39064. this._meshes = [];
  39065. this._scene = scene;
  39066. //Init vertex buffer cache
  39067. this._vertexBuffers = {};
  39068. this._indices = [];
  39069. this._updatable = updatable;
  39070. // vertexData
  39071. if (vertexData) {
  39072. this.setAllVerticesData(vertexData, updatable);
  39073. }
  39074. else {
  39075. this._totalVertices = 0;
  39076. this._indices = [];
  39077. }
  39078. if (this._engine.getCaps().vertexArrayObject) {
  39079. this._vertexArrayObjects = {};
  39080. }
  39081. // applyToMesh
  39082. if (mesh) {
  39083. if (mesh.getClassName() === "LinesMesh") {
  39084. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39085. this._updateExtend();
  39086. }
  39087. this.applyToMesh(mesh);
  39088. mesh.computeWorldMatrix(true);
  39089. }
  39090. }
  39091. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39092. /**
  39093. * 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
  39094. */
  39095. get: function () {
  39096. return this._boundingBias;
  39097. },
  39098. /**
  39099. * 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
  39100. */
  39101. set: function (value) {
  39102. if (this._boundingBias && this._boundingBias.equals(value)) {
  39103. return;
  39104. }
  39105. this._boundingBias = value.clone();
  39106. this._updateBoundingInfo(true, null);
  39107. },
  39108. enumerable: true,
  39109. configurable: true
  39110. });
  39111. /**
  39112. * Static function used to attach a new empty geometry to a mesh
  39113. * @param mesh defines the mesh to attach the geometry to
  39114. * @returns the new {BABYLON.Geometry}
  39115. */
  39116. Geometry.CreateGeometryForMesh = function (mesh) {
  39117. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39118. geometry.applyToMesh(mesh);
  39119. return geometry;
  39120. };
  39121. Object.defineProperty(Geometry.prototype, "extend", {
  39122. /**
  39123. * Gets the current extend of the geometry
  39124. */
  39125. get: function () {
  39126. return this._extend;
  39127. },
  39128. enumerable: true,
  39129. configurable: true
  39130. });
  39131. /**
  39132. * Gets the hosting scene
  39133. * @returns the hosting {BABYLON.Scene}
  39134. */
  39135. Geometry.prototype.getScene = function () {
  39136. return this._scene;
  39137. };
  39138. /**
  39139. * Gets the hosting engine
  39140. * @returns the hosting {BABYLON.Engine}
  39141. */
  39142. Geometry.prototype.getEngine = function () {
  39143. return this._engine;
  39144. };
  39145. /**
  39146. * Defines if the geometry is ready to use
  39147. * @returns true if the geometry is ready to be used
  39148. */
  39149. Geometry.prototype.isReady = function () {
  39150. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39151. };
  39152. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39153. /**
  39154. * Gets a value indicating that the geometry should not be serialized
  39155. */
  39156. get: function () {
  39157. for (var index = 0; index < this._meshes.length; index++) {
  39158. if (!this._meshes[index].doNotSerialize) {
  39159. return false;
  39160. }
  39161. }
  39162. return true;
  39163. },
  39164. enumerable: true,
  39165. configurable: true
  39166. });
  39167. /** @hidden */
  39168. Geometry.prototype._rebuild = function () {
  39169. if (this._vertexArrayObjects) {
  39170. this._vertexArrayObjects = {};
  39171. }
  39172. // Index buffer
  39173. if (this._meshes.length !== 0 && this._indices) {
  39174. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39175. }
  39176. // Vertex buffers
  39177. for (var key in this._vertexBuffers) {
  39178. var vertexBuffer = this._vertexBuffers[key];
  39179. vertexBuffer._rebuild();
  39180. }
  39181. };
  39182. /**
  39183. * Affects all geometry data in one call
  39184. * @param vertexData defines the geometry data
  39185. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39186. */
  39187. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39188. vertexData.applyToGeometry(this, updatable);
  39189. this.notifyUpdate();
  39190. };
  39191. /**
  39192. * Set specific vertex data
  39193. * @param kind defines the data kind (Position, normal, etc...)
  39194. * @param data defines the vertex data to use
  39195. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39196. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39197. */
  39198. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39199. if (updatable === void 0) { updatable = false; }
  39200. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39201. this.setVerticesBuffer(buffer);
  39202. };
  39203. /**
  39204. * Removes a specific vertex data
  39205. * @param kind defines the data kind (Position, normal, etc...)
  39206. */
  39207. Geometry.prototype.removeVerticesData = function (kind) {
  39208. if (this._vertexBuffers[kind]) {
  39209. this._vertexBuffers[kind].dispose();
  39210. delete this._vertexBuffers[kind];
  39211. }
  39212. };
  39213. /**
  39214. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39215. * @param buffer defines the vertex buffer to use
  39216. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39217. */
  39218. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39219. if (totalVertices === void 0) { totalVertices = null; }
  39220. var kind = buffer.getKind();
  39221. if (this._vertexBuffers[kind]) {
  39222. this._vertexBuffers[kind].dispose();
  39223. }
  39224. this._vertexBuffers[kind] = buffer;
  39225. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39226. var data = buffer.getData();
  39227. if (totalVertices != null) {
  39228. this._totalVertices = totalVertices;
  39229. }
  39230. else {
  39231. if (data != null) {
  39232. this._totalVertices = data.length / (buffer.byteStride / 4);
  39233. }
  39234. }
  39235. this._updateExtend(data);
  39236. this._resetPointsArrayCache();
  39237. var meshes = this._meshes;
  39238. var numOfMeshes = meshes.length;
  39239. for (var index = 0; index < numOfMeshes; index++) {
  39240. var mesh = meshes[index];
  39241. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39242. mesh._createGlobalSubMesh(false);
  39243. mesh.computeWorldMatrix(true);
  39244. }
  39245. }
  39246. this.notifyUpdate(kind);
  39247. if (this._vertexArrayObjects) {
  39248. this._disposeVertexArrayObjects();
  39249. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39250. }
  39251. };
  39252. /**
  39253. * Update a specific vertex buffer
  39254. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39255. * It will do nothing if the buffer is not updatable
  39256. * @param kind defines the data kind (Position, normal, etc...)
  39257. * @param data defines the data to use
  39258. * @param offset defines the offset in the target buffer where to store the data
  39259. * @param useBytes set to true if the offset is in bytes
  39260. */
  39261. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39262. if (useBytes === void 0) { useBytes = false; }
  39263. var vertexBuffer = this.getVertexBuffer(kind);
  39264. if (!vertexBuffer) {
  39265. return;
  39266. }
  39267. vertexBuffer.updateDirectly(data, offset, useBytes);
  39268. this.notifyUpdate(kind);
  39269. };
  39270. /**
  39271. * Update a specific vertex buffer
  39272. * This function will create a new buffer if the current one is not updatable
  39273. * @param kind defines the data kind (Position, normal, etc...)
  39274. * @param data defines the data to use
  39275. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39276. */
  39277. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39278. if (updateExtends === void 0) { updateExtends = false; }
  39279. var vertexBuffer = this.getVertexBuffer(kind);
  39280. if (!vertexBuffer) {
  39281. return;
  39282. }
  39283. vertexBuffer.update(data);
  39284. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39285. this._updateBoundingInfo(updateExtends, data);
  39286. }
  39287. this.notifyUpdate(kind);
  39288. };
  39289. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39290. if (updateExtends) {
  39291. this._updateExtend(data);
  39292. }
  39293. var meshes = this._meshes;
  39294. var numOfMeshes = meshes.length;
  39295. this._resetPointsArrayCache();
  39296. for (var index = 0; index < numOfMeshes; index++) {
  39297. var mesh = meshes[index];
  39298. if (updateExtends) {
  39299. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39300. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39301. var subMesh = mesh.subMeshes[subIndex];
  39302. subMesh.refreshBoundingInfo();
  39303. }
  39304. }
  39305. }
  39306. };
  39307. /** @hidden */
  39308. Geometry.prototype._bind = function (effect, indexToBind) {
  39309. if (!effect) {
  39310. return;
  39311. }
  39312. if (indexToBind === undefined) {
  39313. indexToBind = this._indexBuffer;
  39314. }
  39315. var vbs = this.getVertexBuffers();
  39316. if (!vbs) {
  39317. return;
  39318. }
  39319. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39320. this._engine.bindBuffers(vbs, indexToBind, effect);
  39321. return;
  39322. }
  39323. // Using VAO
  39324. if (!this._vertexArrayObjects[effect.key]) {
  39325. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39326. }
  39327. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39328. };
  39329. /**
  39330. * Gets total number of vertices
  39331. * @returns the total number of vertices
  39332. */
  39333. Geometry.prototype.getTotalVertices = function () {
  39334. if (!this.isReady()) {
  39335. return 0;
  39336. }
  39337. return this._totalVertices;
  39338. };
  39339. /**
  39340. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39341. * @param kind defines the data kind (Position, normal, etc...)
  39342. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39343. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39344. * @returns a float array containing vertex data
  39345. */
  39346. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39347. var vertexBuffer = this.getVertexBuffer(kind);
  39348. if (!vertexBuffer) {
  39349. return null;
  39350. }
  39351. var data = vertexBuffer.getData();
  39352. if (!data) {
  39353. return null;
  39354. }
  39355. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39356. var count = this._totalVertices * vertexBuffer.getSize();
  39357. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39358. var copy_1 = new Array(count);
  39359. vertexBuffer.forEach(count, function (value, index) {
  39360. copy_1[index] = value;
  39361. });
  39362. return copy_1;
  39363. }
  39364. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39365. if (data instanceof Array) {
  39366. var offset = vertexBuffer.byteOffset / 4;
  39367. return BABYLON.Tools.Slice(data, offset, offset + count);
  39368. }
  39369. else if (data instanceof ArrayBuffer) {
  39370. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39371. }
  39372. else {
  39373. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39374. }
  39375. }
  39376. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39377. return BABYLON.Tools.Slice(data);
  39378. }
  39379. return data;
  39380. };
  39381. /**
  39382. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39383. * @param kind defines the data kind (Position, normal, etc...)
  39384. * @returns true if the vertex buffer with the specified kind is updatable
  39385. */
  39386. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39387. var vb = this._vertexBuffers[kind];
  39388. if (!vb) {
  39389. return false;
  39390. }
  39391. return vb.isUpdatable();
  39392. };
  39393. /**
  39394. * Gets a specific vertex buffer
  39395. * @param kind defines the data kind (Position, normal, etc...)
  39396. * @returns a {BABYLON.VertexBuffer}
  39397. */
  39398. Geometry.prototype.getVertexBuffer = function (kind) {
  39399. if (!this.isReady()) {
  39400. return null;
  39401. }
  39402. return this._vertexBuffers[kind];
  39403. };
  39404. /**
  39405. * Returns all vertex buffers
  39406. * @return an object holding all vertex buffers indexed by kind
  39407. */
  39408. Geometry.prototype.getVertexBuffers = function () {
  39409. if (!this.isReady()) {
  39410. return null;
  39411. }
  39412. return this._vertexBuffers;
  39413. };
  39414. /**
  39415. * Gets a boolean indicating if specific vertex buffer is present
  39416. * @param kind defines the data kind (Position, normal, etc...)
  39417. * @returns true if data is present
  39418. */
  39419. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39420. if (!this._vertexBuffers) {
  39421. if (this._delayInfo) {
  39422. return this._delayInfo.indexOf(kind) !== -1;
  39423. }
  39424. return false;
  39425. }
  39426. return this._vertexBuffers[kind] !== undefined;
  39427. };
  39428. /**
  39429. * Gets a list of all attached data kinds (Position, normal, etc...)
  39430. * @returns a list of string containing all kinds
  39431. */
  39432. Geometry.prototype.getVerticesDataKinds = function () {
  39433. var result = [];
  39434. var kind;
  39435. if (!this._vertexBuffers && this._delayInfo) {
  39436. for (kind in this._delayInfo) {
  39437. result.push(kind);
  39438. }
  39439. }
  39440. else {
  39441. for (kind in this._vertexBuffers) {
  39442. result.push(kind);
  39443. }
  39444. }
  39445. return result;
  39446. };
  39447. /**
  39448. * Update index buffer
  39449. * @param indices defines the indices to store in the index buffer
  39450. * @param offset defines the offset in the target buffer where to store the data
  39451. */
  39452. Geometry.prototype.updateIndices = function (indices, offset) {
  39453. if (!this._indexBuffer) {
  39454. return;
  39455. }
  39456. if (!this._indexBufferIsUpdatable) {
  39457. this.setIndices(indices, null, true);
  39458. }
  39459. else {
  39460. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39461. }
  39462. };
  39463. /**
  39464. * Creates a new index buffer
  39465. * @param indices defines the indices to store in the index buffer
  39466. * @param totalVertices defines the total number of vertices (could be null)
  39467. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39468. */
  39469. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39470. if (totalVertices === void 0) { totalVertices = null; }
  39471. if (updatable === void 0) { updatable = false; }
  39472. if (this._indexBuffer) {
  39473. this._engine._releaseBuffer(this._indexBuffer);
  39474. }
  39475. this._disposeVertexArrayObjects();
  39476. this._indices = indices;
  39477. this._indexBufferIsUpdatable = updatable;
  39478. if (this._meshes.length !== 0 && this._indices) {
  39479. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39480. }
  39481. if (totalVertices != undefined) { // including null and undefined
  39482. this._totalVertices = totalVertices;
  39483. }
  39484. var meshes = this._meshes;
  39485. var numOfMeshes = meshes.length;
  39486. for (var index = 0; index < numOfMeshes; index++) {
  39487. meshes[index]._createGlobalSubMesh(true);
  39488. }
  39489. this.notifyUpdate();
  39490. };
  39491. /**
  39492. * Return the total number of indices
  39493. * @returns the total number of indices
  39494. */
  39495. Geometry.prototype.getTotalIndices = function () {
  39496. if (!this.isReady()) {
  39497. return 0;
  39498. }
  39499. return this._indices.length;
  39500. };
  39501. /**
  39502. * Gets the index buffer array
  39503. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39504. * @returns the index buffer array
  39505. */
  39506. Geometry.prototype.getIndices = function (copyWhenShared) {
  39507. if (!this.isReady()) {
  39508. return null;
  39509. }
  39510. var orig = this._indices;
  39511. if (!copyWhenShared || this._meshes.length === 1) {
  39512. return orig;
  39513. }
  39514. else {
  39515. var len = orig.length;
  39516. var copy = [];
  39517. for (var i = 0; i < len; i++) {
  39518. copy.push(orig[i]);
  39519. }
  39520. return copy;
  39521. }
  39522. };
  39523. /**
  39524. * Gets the index buffer
  39525. * @return the index buffer
  39526. */
  39527. Geometry.prototype.getIndexBuffer = function () {
  39528. if (!this.isReady()) {
  39529. return null;
  39530. }
  39531. return this._indexBuffer;
  39532. };
  39533. /** @hidden */
  39534. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39535. if (effect === void 0) { effect = null; }
  39536. if (!effect || !this._vertexArrayObjects) {
  39537. return;
  39538. }
  39539. if (this._vertexArrayObjects[effect.key]) {
  39540. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39541. delete this._vertexArrayObjects[effect.key];
  39542. }
  39543. };
  39544. /**
  39545. * Release the associated resources for a specific mesh
  39546. * @param mesh defines the source mesh
  39547. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39548. */
  39549. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39550. var meshes = this._meshes;
  39551. var index = meshes.indexOf(mesh);
  39552. if (index === -1) {
  39553. return;
  39554. }
  39555. meshes.splice(index, 1);
  39556. mesh._geometry = null;
  39557. if (meshes.length === 0 && shouldDispose) {
  39558. this.dispose();
  39559. }
  39560. };
  39561. /**
  39562. * Apply current geometry to a given mesh
  39563. * @param mesh defines the mesh to apply geometry to
  39564. */
  39565. Geometry.prototype.applyToMesh = function (mesh) {
  39566. if (mesh._geometry === this) {
  39567. return;
  39568. }
  39569. var previousGeometry = mesh._geometry;
  39570. if (previousGeometry) {
  39571. previousGeometry.releaseForMesh(mesh);
  39572. }
  39573. var meshes = this._meshes;
  39574. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39575. mesh._geometry = this;
  39576. this._scene.pushGeometry(this);
  39577. meshes.push(mesh);
  39578. if (this.isReady()) {
  39579. this._applyToMesh(mesh);
  39580. }
  39581. else {
  39582. mesh._boundingInfo = this._boundingInfo;
  39583. }
  39584. };
  39585. Geometry.prototype._updateExtend = function (data) {
  39586. if (data === void 0) { data = null; }
  39587. if (!data) {
  39588. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39589. }
  39590. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39591. };
  39592. Geometry.prototype._applyToMesh = function (mesh) {
  39593. var numOfMeshes = this._meshes.length;
  39594. // vertexBuffers
  39595. for (var kind in this._vertexBuffers) {
  39596. if (numOfMeshes === 1) {
  39597. this._vertexBuffers[kind].create();
  39598. }
  39599. var buffer = this._vertexBuffers[kind].getBuffer();
  39600. if (buffer)
  39601. buffer.references = numOfMeshes;
  39602. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39603. if (!this._extend) {
  39604. this._updateExtend();
  39605. }
  39606. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39607. mesh._createGlobalSubMesh(false);
  39608. //bounding info was just created again, world matrix should be applied again.
  39609. mesh._updateBoundingInfo();
  39610. }
  39611. }
  39612. // indexBuffer
  39613. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39614. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39615. }
  39616. if (this._indexBuffer) {
  39617. this._indexBuffer.references = numOfMeshes;
  39618. }
  39619. };
  39620. Geometry.prototype.notifyUpdate = function (kind) {
  39621. if (this.onGeometryUpdated) {
  39622. this.onGeometryUpdated(this, kind);
  39623. }
  39624. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39625. var mesh = _a[_i];
  39626. mesh._markSubMeshesAsAttributesDirty();
  39627. }
  39628. };
  39629. /**
  39630. * Load the geometry if it was flagged as delay loaded
  39631. * @param scene defines the hosting scene
  39632. * @param onLoaded defines a callback called when the geometry is loaded
  39633. */
  39634. Geometry.prototype.load = function (scene, onLoaded) {
  39635. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39636. return;
  39637. }
  39638. if (this.isReady()) {
  39639. if (onLoaded) {
  39640. onLoaded();
  39641. }
  39642. return;
  39643. }
  39644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39645. this._queueLoad(scene, onLoaded);
  39646. };
  39647. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39648. var _this = this;
  39649. if (!this.delayLoadingFile) {
  39650. return;
  39651. }
  39652. scene._addPendingData(this);
  39653. scene._loadFile(this.delayLoadingFile, function (data) {
  39654. if (!_this._delayLoadingFunction) {
  39655. return;
  39656. }
  39657. _this._delayLoadingFunction(JSON.parse(data), _this);
  39658. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39659. _this._delayInfo = [];
  39660. scene._removePendingData(_this);
  39661. var meshes = _this._meshes;
  39662. var numOfMeshes = meshes.length;
  39663. for (var index = 0; index < numOfMeshes; index++) {
  39664. _this._applyToMesh(meshes[index]);
  39665. }
  39666. if (onLoaded) {
  39667. onLoaded();
  39668. }
  39669. }, undefined, true);
  39670. };
  39671. /**
  39672. * Invert the geometry to move from a right handed system to a left handed one.
  39673. */
  39674. Geometry.prototype.toLeftHanded = function () {
  39675. // Flip faces
  39676. var tIndices = this.getIndices(false);
  39677. if (tIndices != null && tIndices.length > 0) {
  39678. for (var i = 0; i < tIndices.length; i += 3) {
  39679. var tTemp = tIndices[i + 0];
  39680. tIndices[i + 0] = tIndices[i + 2];
  39681. tIndices[i + 2] = tTemp;
  39682. }
  39683. this.setIndices(tIndices);
  39684. }
  39685. // Negate position.z
  39686. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39687. if (tPositions != null && tPositions.length > 0) {
  39688. for (var i = 0; i < tPositions.length; i += 3) {
  39689. tPositions[i + 2] = -tPositions[i + 2];
  39690. }
  39691. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39692. }
  39693. // Negate normal.z
  39694. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39695. if (tNormals != null && tNormals.length > 0) {
  39696. for (var i = 0; i < tNormals.length; i += 3) {
  39697. tNormals[i + 2] = -tNormals[i + 2];
  39698. }
  39699. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39700. }
  39701. };
  39702. // Cache
  39703. /** @hidden */
  39704. Geometry.prototype._resetPointsArrayCache = function () {
  39705. this._positions = null;
  39706. };
  39707. /** @hidden */
  39708. Geometry.prototype._generatePointsArray = function () {
  39709. if (this._positions)
  39710. return true;
  39711. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39712. if (!data || data.length === 0) {
  39713. return false;
  39714. }
  39715. this._positions = [];
  39716. for (var index = 0; index < data.length; index += 3) {
  39717. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39718. }
  39719. return true;
  39720. };
  39721. /**
  39722. * Gets a value indicating if the geometry is disposed
  39723. * @returns true if the geometry was disposed
  39724. */
  39725. Geometry.prototype.isDisposed = function () {
  39726. return this._isDisposed;
  39727. };
  39728. Geometry.prototype._disposeVertexArrayObjects = function () {
  39729. if (this._vertexArrayObjects) {
  39730. for (var kind in this._vertexArrayObjects) {
  39731. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39732. }
  39733. this._vertexArrayObjects = {};
  39734. }
  39735. };
  39736. /**
  39737. * Free all associated resources
  39738. */
  39739. Geometry.prototype.dispose = function () {
  39740. var meshes = this._meshes;
  39741. var numOfMeshes = meshes.length;
  39742. var index;
  39743. for (index = 0; index < numOfMeshes; index++) {
  39744. this.releaseForMesh(meshes[index]);
  39745. }
  39746. this._meshes = [];
  39747. this._disposeVertexArrayObjects();
  39748. for (var kind in this._vertexBuffers) {
  39749. this._vertexBuffers[kind].dispose();
  39750. }
  39751. this._vertexBuffers = {};
  39752. this._totalVertices = 0;
  39753. if (this._indexBuffer) {
  39754. this._engine._releaseBuffer(this._indexBuffer);
  39755. }
  39756. this._indexBuffer = null;
  39757. this._indices = [];
  39758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39759. this.delayLoadingFile = null;
  39760. this._delayLoadingFunction = null;
  39761. this._delayInfo = [];
  39762. this._boundingInfo = null;
  39763. this._scene.removeGeometry(this);
  39764. this._isDisposed = true;
  39765. };
  39766. /**
  39767. * Clone the current geometry into a new geometry
  39768. * @param id defines the unique ID of the new geometry
  39769. * @returns a new geometry object
  39770. */
  39771. Geometry.prototype.copy = function (id) {
  39772. var vertexData = new BABYLON.VertexData();
  39773. vertexData.indices = [];
  39774. var indices = this.getIndices();
  39775. if (indices) {
  39776. for (var index = 0; index < indices.length; index++) {
  39777. vertexData.indices.push(indices[index]);
  39778. }
  39779. }
  39780. var updatable = false;
  39781. var stopChecking = false;
  39782. var kind;
  39783. for (kind in this._vertexBuffers) {
  39784. // using slice() to make a copy of the array and not just reference it
  39785. var data = this.getVerticesData(kind);
  39786. if (data instanceof Float32Array) {
  39787. vertexData.set(new Float32Array(data), kind);
  39788. }
  39789. else {
  39790. vertexData.set(data.slice(0), kind);
  39791. }
  39792. if (!stopChecking) {
  39793. var vb = this.getVertexBuffer(kind);
  39794. if (vb) {
  39795. updatable = vb.isUpdatable();
  39796. stopChecking = !updatable;
  39797. }
  39798. }
  39799. }
  39800. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39801. geometry.delayLoadState = this.delayLoadState;
  39802. geometry.delayLoadingFile = this.delayLoadingFile;
  39803. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39804. for (kind in this._delayInfo) {
  39805. geometry._delayInfo = geometry._delayInfo || [];
  39806. geometry._delayInfo.push(kind);
  39807. }
  39808. // Bounding info
  39809. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39810. return geometry;
  39811. };
  39812. /**
  39813. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39814. * @return a JSON representation of the current geometry data (without the vertices data)
  39815. */
  39816. Geometry.prototype.serialize = function () {
  39817. var serializationObject = {};
  39818. serializationObject.id = this.id;
  39819. serializationObject.updatable = this._updatable;
  39820. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39821. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39822. }
  39823. return serializationObject;
  39824. };
  39825. Geometry.prototype.toNumberArray = function (origin) {
  39826. if (Array.isArray(origin)) {
  39827. return origin;
  39828. }
  39829. else {
  39830. return Array.prototype.slice.call(origin);
  39831. }
  39832. };
  39833. /**
  39834. * Serialize all vertices data into a JSON oject
  39835. * @returns a JSON representation of the current geometry data
  39836. */
  39837. Geometry.prototype.serializeVerticeData = function () {
  39838. var serializationObject = this.serialize();
  39839. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39840. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39841. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39842. serializationObject.positions._updatable = true;
  39843. }
  39844. }
  39845. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39846. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39847. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39848. serializationObject.normals._updatable = true;
  39849. }
  39850. }
  39851. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39852. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39853. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39854. serializationObject.tangets._updatable = true;
  39855. }
  39856. }
  39857. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39858. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39859. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39860. serializationObject.uvs._updatable = true;
  39861. }
  39862. }
  39863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39864. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39865. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39866. serializationObject.uv2s._updatable = true;
  39867. }
  39868. }
  39869. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39870. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39871. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39872. serializationObject.uv3s._updatable = true;
  39873. }
  39874. }
  39875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39876. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39877. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39878. serializationObject.uv4s._updatable = true;
  39879. }
  39880. }
  39881. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39882. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39883. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39884. serializationObject.uv5s._updatable = true;
  39885. }
  39886. }
  39887. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39888. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39889. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39890. serializationObject.uv6s._updatable = true;
  39891. }
  39892. }
  39893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39894. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39895. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39896. serializationObject.colors._updatable = true;
  39897. }
  39898. }
  39899. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39900. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39901. serializationObject.matricesIndices._isExpanded = true;
  39902. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39903. serializationObject.matricesIndices._updatable = true;
  39904. }
  39905. }
  39906. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39907. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39908. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39909. serializationObject.matricesWeights._updatable = true;
  39910. }
  39911. }
  39912. serializationObject.indices = this.toNumberArray(this.getIndices());
  39913. return serializationObject;
  39914. };
  39915. // Statics
  39916. /**
  39917. * Extracts a clone of a mesh geometry
  39918. * @param mesh defines the source mesh
  39919. * @param id defines the unique ID of the new geometry object
  39920. * @returns the new geometry object
  39921. */
  39922. Geometry.ExtractFromMesh = function (mesh, id) {
  39923. var geometry = mesh._geometry;
  39924. if (!geometry) {
  39925. return null;
  39926. }
  39927. return geometry.copy(id);
  39928. };
  39929. /**
  39930. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39931. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39932. * Be aware Math.random() could cause collisions, but:
  39933. * "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"
  39934. * @returns a string containing a new GUID
  39935. */
  39936. Geometry.RandomId = function () {
  39937. return BABYLON.Tools.RandomId();
  39938. };
  39939. /** @hidden */
  39940. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39941. var scene = mesh.getScene();
  39942. // Geometry
  39943. var geometryId = parsedGeometry.geometryId;
  39944. if (geometryId) {
  39945. var geometry = scene.getGeometryByID(geometryId);
  39946. if (geometry) {
  39947. geometry.applyToMesh(mesh);
  39948. }
  39949. }
  39950. else if (parsedGeometry instanceof ArrayBuffer) {
  39951. var binaryInfo = mesh._binaryInfo;
  39952. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39953. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39954. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39955. }
  39956. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39957. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39959. }
  39960. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39961. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39963. }
  39964. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39965. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39967. }
  39968. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39969. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39971. }
  39972. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39973. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39974. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39975. }
  39976. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39977. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39979. }
  39980. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39981. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39983. }
  39984. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39985. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39986. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39987. }
  39988. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39989. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39991. }
  39992. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39993. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39994. var floatIndices = [];
  39995. for (var i = 0; i < matricesIndicesData.length; i++) {
  39996. var index = matricesIndicesData[i];
  39997. floatIndices.push(index & 0x000000FF);
  39998. floatIndices.push((index & 0x0000FF00) >> 8);
  39999. floatIndices.push((index & 0x00FF0000) >> 16);
  40000. floatIndices.push(index >> 24);
  40001. }
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40003. }
  40004. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40005. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40006. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40007. }
  40008. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40009. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40010. mesh.setIndices(indicesData, null);
  40011. }
  40012. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40013. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40014. mesh.subMeshes = [];
  40015. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40016. var materialIndex = subMeshesData[(i * 5) + 0];
  40017. var verticesStart = subMeshesData[(i * 5) + 1];
  40018. var verticesCount = subMeshesData[(i * 5) + 2];
  40019. var indexStart = subMeshesData[(i * 5) + 3];
  40020. var indexCount = subMeshesData[(i * 5) + 4];
  40021. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40022. }
  40023. }
  40024. }
  40025. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40027. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40028. if (parsedGeometry.tangents) {
  40029. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40030. }
  40031. if (parsedGeometry.uvs) {
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40033. }
  40034. if (parsedGeometry.uvs2) {
  40035. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40036. }
  40037. if (parsedGeometry.uvs3) {
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40039. }
  40040. if (parsedGeometry.uvs4) {
  40041. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40042. }
  40043. if (parsedGeometry.uvs5) {
  40044. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40045. }
  40046. if (parsedGeometry.uvs6) {
  40047. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40048. }
  40049. if (parsedGeometry.colors) {
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40051. }
  40052. if (parsedGeometry.matricesIndices) {
  40053. if (!parsedGeometry.matricesIndices._isExpanded) {
  40054. var floatIndices = [];
  40055. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40056. var matricesIndex = parsedGeometry.matricesIndices[i];
  40057. floatIndices.push(matricesIndex & 0x000000FF);
  40058. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40059. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40060. floatIndices.push(matricesIndex >> 24);
  40061. }
  40062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40063. }
  40064. else {
  40065. delete parsedGeometry.matricesIndices._isExpanded;
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40067. }
  40068. }
  40069. if (parsedGeometry.matricesIndicesExtra) {
  40070. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40071. var floatIndices = [];
  40072. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40073. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40074. floatIndices.push(matricesIndex & 0x000000FF);
  40075. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40076. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40077. floatIndices.push(matricesIndex >> 24);
  40078. }
  40079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40080. }
  40081. else {
  40082. delete parsedGeometry.matricesIndices._isExpanded;
  40083. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40084. }
  40085. }
  40086. if (parsedGeometry.matricesWeights) {
  40087. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40089. }
  40090. if (parsedGeometry.matricesWeightsExtra) {
  40091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40092. }
  40093. mesh.setIndices(parsedGeometry.indices, null);
  40094. }
  40095. // SubMeshes
  40096. if (parsedGeometry.subMeshes) {
  40097. mesh.subMeshes = [];
  40098. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40099. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40100. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40101. }
  40102. }
  40103. // Flat shading
  40104. if (mesh._shouldGenerateFlatShading) {
  40105. mesh.convertToFlatShadedMesh();
  40106. delete mesh._shouldGenerateFlatShading;
  40107. }
  40108. // Update
  40109. mesh.computeWorldMatrix(true);
  40110. // Octree
  40111. var sceneOctree = scene.selectionOctree;
  40112. if (sceneOctree !== undefined && sceneOctree !== null) {
  40113. sceneOctree.addMesh(mesh);
  40114. }
  40115. };
  40116. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40117. var epsilon = 1e-3;
  40118. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40119. return;
  40120. }
  40121. var noInfluenceBoneIndex = 0.0;
  40122. if (parsedGeometry.skeletonId > -1) {
  40123. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40124. if (!skeleton) {
  40125. return;
  40126. }
  40127. noInfluenceBoneIndex = skeleton.bones.length;
  40128. }
  40129. else {
  40130. return;
  40131. }
  40132. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40133. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40134. var matricesWeights = parsedGeometry.matricesWeights;
  40135. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40136. var influencers = parsedGeometry.numBoneInfluencer;
  40137. var size = matricesWeights.length;
  40138. for (var i = 0; i < size; i += 4) {
  40139. var weight = 0.0;
  40140. var firstZeroWeight = -1;
  40141. for (var j = 0; j < 4; j++) {
  40142. var w = matricesWeights[i + j];
  40143. weight += w;
  40144. if (w < epsilon && firstZeroWeight < 0) {
  40145. firstZeroWeight = j;
  40146. }
  40147. }
  40148. if (matricesWeightsExtra) {
  40149. for (var j = 0; j < 4; j++) {
  40150. var w = matricesWeightsExtra[i + j];
  40151. weight += w;
  40152. if (w < epsilon && firstZeroWeight < 0) {
  40153. firstZeroWeight = j + 4;
  40154. }
  40155. }
  40156. }
  40157. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40158. firstZeroWeight = influencers - 1;
  40159. }
  40160. if (weight > epsilon) {
  40161. var mweight = 1.0 / weight;
  40162. for (var j = 0; j < 4; j++) {
  40163. matricesWeights[i + j] *= mweight;
  40164. }
  40165. if (matricesWeightsExtra) {
  40166. for (var j = 0; j < 4; j++) {
  40167. matricesWeightsExtra[i + j] *= mweight;
  40168. }
  40169. }
  40170. }
  40171. else {
  40172. if (firstZeroWeight >= 4) {
  40173. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40174. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40175. }
  40176. else {
  40177. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40178. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40179. }
  40180. }
  40181. }
  40182. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40183. if (parsedGeometry.matricesWeightsExtra) {
  40184. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40185. }
  40186. };
  40187. /**
  40188. * Create a new geometry from persisted data (Using .babylon file format)
  40189. * @param parsedVertexData defines the persisted data
  40190. * @param scene defines the hosting scene
  40191. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40192. * @returns the new geometry object
  40193. */
  40194. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40195. if (scene.getGeometryByID(parsedVertexData.id)) {
  40196. return null; // null since geometry could be something else than a box...
  40197. }
  40198. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40199. if (BABYLON.Tags) {
  40200. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40201. }
  40202. if (parsedVertexData.delayLoadingFile) {
  40203. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40204. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40205. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40206. geometry._delayInfo = [];
  40207. if (parsedVertexData.hasUVs) {
  40208. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40209. }
  40210. if (parsedVertexData.hasUVs2) {
  40211. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40212. }
  40213. if (parsedVertexData.hasUVs3) {
  40214. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40215. }
  40216. if (parsedVertexData.hasUVs4) {
  40217. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40218. }
  40219. if (parsedVertexData.hasUVs5) {
  40220. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40221. }
  40222. if (parsedVertexData.hasUVs6) {
  40223. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40224. }
  40225. if (parsedVertexData.hasColors) {
  40226. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40227. }
  40228. if (parsedVertexData.hasMatricesIndices) {
  40229. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40230. }
  40231. if (parsedVertexData.hasMatricesWeights) {
  40232. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40233. }
  40234. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40235. }
  40236. else {
  40237. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40238. }
  40239. scene.pushGeometry(geometry, true);
  40240. return geometry;
  40241. };
  40242. return Geometry;
  40243. }());
  40244. BABYLON.Geometry = Geometry;
  40245. // Primitives
  40246. /// Abstract class
  40247. /**
  40248. * Abstract class used to provide common services for all typed geometries
  40249. * @hidden
  40250. */
  40251. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40252. __extends(_PrimitiveGeometry, _super);
  40253. /**
  40254. * Creates a new typed geometry
  40255. * @param id defines the unique ID of the geometry
  40256. * @param scene defines the hosting scene
  40257. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40258. * @param mesh defines the hosting mesh (can be null)
  40259. */
  40260. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40261. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40262. if (mesh === void 0) { mesh = null; }
  40263. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40264. _this._canBeRegenerated = _canBeRegenerated;
  40265. _this._beingRegenerated = true;
  40266. _this.regenerate();
  40267. _this._beingRegenerated = false;
  40268. return _this;
  40269. }
  40270. /**
  40271. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40272. * @returns true if the geometry can be regenerated
  40273. */
  40274. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40275. return this._canBeRegenerated;
  40276. };
  40277. /**
  40278. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40279. */
  40280. _PrimitiveGeometry.prototype.regenerate = function () {
  40281. if (!this._canBeRegenerated) {
  40282. return;
  40283. }
  40284. this._beingRegenerated = true;
  40285. this.setAllVerticesData(this._regenerateVertexData(), false);
  40286. this._beingRegenerated = false;
  40287. };
  40288. /**
  40289. * Clone the geometry
  40290. * @param id defines the unique ID of the new geometry
  40291. * @returns the new geometry
  40292. */
  40293. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40294. return _super.prototype.copy.call(this, id);
  40295. };
  40296. // overrides
  40297. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40298. if (!this._beingRegenerated) {
  40299. return;
  40300. }
  40301. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40302. };
  40303. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40304. if (!this._beingRegenerated) {
  40305. return;
  40306. }
  40307. _super.prototype.setVerticesData.call(this, kind, data, false);
  40308. };
  40309. // to override
  40310. /** @hidden */
  40311. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40312. throw new Error("Abstract method");
  40313. };
  40314. _PrimitiveGeometry.prototype.copy = function (id) {
  40315. throw new Error("Must be overriden in sub-classes.");
  40316. };
  40317. _PrimitiveGeometry.prototype.serialize = function () {
  40318. var serializationObject = _super.prototype.serialize.call(this);
  40319. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40320. return serializationObject;
  40321. };
  40322. return _PrimitiveGeometry;
  40323. }(Geometry));
  40324. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40325. /**
  40326. * Creates a ribbon geometry
  40327. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40328. */
  40329. var RibbonGeometry = /** @class */ (function (_super) {
  40330. __extends(RibbonGeometry, _super);
  40331. /**
  40332. * Creates a ribbon geometry
  40333. * @param id defines the unique ID of the geometry
  40334. * @param scene defines the hosting scene
  40335. * @param pathArray defines the array of paths to use
  40336. * @param closeArray defines if the last path and the first path must be joined
  40337. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40338. * @param offset defines the offset between points
  40339. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40340. * @param mesh defines the hosting mesh (can be null)
  40341. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40342. */
  40343. function RibbonGeometry(id, scene,
  40344. /**
  40345. * Defines the array of paths to use
  40346. */
  40347. pathArray,
  40348. /**
  40349. * Defines if the last and first points of each path in your pathArray must be joined
  40350. */
  40351. closeArray,
  40352. /**
  40353. * Defines if the last and first points of each path in your pathArray must be joined
  40354. */
  40355. closePath,
  40356. /**
  40357. * Defines the offset between points
  40358. */
  40359. offset, canBeRegenerated, mesh,
  40360. /**
  40361. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40362. */
  40363. side) {
  40364. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40365. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40366. _this.pathArray = pathArray;
  40367. _this.closeArray = closeArray;
  40368. _this.closePath = closePath;
  40369. _this.offset = offset;
  40370. _this.side = side;
  40371. return _this;
  40372. }
  40373. /** @hidden */
  40374. RibbonGeometry.prototype._regenerateVertexData = function () {
  40375. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40376. };
  40377. RibbonGeometry.prototype.copy = function (id) {
  40378. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40379. };
  40380. return RibbonGeometry;
  40381. }(_PrimitiveGeometry));
  40382. BABYLON.RibbonGeometry = RibbonGeometry;
  40383. /**
  40384. * Creates a box geometry
  40385. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40386. */
  40387. var BoxGeometry = /** @class */ (function (_super) {
  40388. __extends(BoxGeometry, _super);
  40389. /**
  40390. * Creates a box geometry
  40391. * @param id defines the unique ID of the geometry
  40392. * @param scene defines the hosting scene
  40393. * @param size defines the zise of the box (width, height and depth are the same)
  40394. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40395. * @param mesh defines the hosting mesh (can be null)
  40396. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40397. */
  40398. function BoxGeometry(id, scene,
  40399. /**
  40400. * Defines the zise of the box (width, height and depth are the same)
  40401. */
  40402. size, canBeRegenerated, mesh,
  40403. /**
  40404. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40405. */
  40406. side) {
  40407. if (mesh === void 0) { mesh = null; }
  40408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40410. _this.size = size;
  40411. _this.side = side;
  40412. return _this;
  40413. }
  40414. BoxGeometry.prototype._regenerateVertexData = function () {
  40415. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40416. };
  40417. BoxGeometry.prototype.copy = function (id) {
  40418. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40419. };
  40420. BoxGeometry.prototype.serialize = function () {
  40421. var serializationObject = _super.prototype.serialize.call(this);
  40422. serializationObject.size = this.size;
  40423. return serializationObject;
  40424. };
  40425. BoxGeometry.Parse = function (parsedBox, scene) {
  40426. if (scene.getGeometryByID(parsedBox.id)) {
  40427. return null; // null since geometry could be something else than a box...
  40428. }
  40429. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40430. if (BABYLON.Tags) {
  40431. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40432. }
  40433. scene.pushGeometry(box, true);
  40434. return box;
  40435. };
  40436. return BoxGeometry;
  40437. }(_PrimitiveGeometry));
  40438. BABYLON.BoxGeometry = BoxGeometry;
  40439. /**
  40440. * Creates a sphere geometry
  40441. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40442. */
  40443. var SphereGeometry = /** @class */ (function (_super) {
  40444. __extends(SphereGeometry, _super);
  40445. /**
  40446. * Create a new sphere geometry
  40447. * @param id defines the unique ID of the geometry
  40448. * @param scene defines the hosting scene
  40449. * @param segments defines the number of segments to use to create the sphere
  40450. * @param diameter defines the diameter of the sphere
  40451. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40452. * @param mesh defines the hosting mesh (can be null)
  40453. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40454. */
  40455. function SphereGeometry(id, scene,
  40456. /**
  40457. * Defines the number of segments to use to create the sphere
  40458. */
  40459. segments,
  40460. /**
  40461. * Defines the diameter of the sphere
  40462. */
  40463. diameter, canBeRegenerated, mesh,
  40464. /**
  40465. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40466. */
  40467. side) {
  40468. if (mesh === void 0) { mesh = null; }
  40469. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40470. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40471. _this.segments = segments;
  40472. _this.diameter = diameter;
  40473. _this.side = side;
  40474. return _this;
  40475. }
  40476. SphereGeometry.prototype._regenerateVertexData = function () {
  40477. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40478. };
  40479. SphereGeometry.prototype.copy = function (id) {
  40480. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40481. };
  40482. SphereGeometry.prototype.serialize = function () {
  40483. var serializationObject = _super.prototype.serialize.call(this);
  40484. serializationObject.segments = this.segments;
  40485. serializationObject.diameter = this.diameter;
  40486. return serializationObject;
  40487. };
  40488. SphereGeometry.Parse = function (parsedSphere, scene) {
  40489. if (scene.getGeometryByID(parsedSphere.id)) {
  40490. return null; // null since geometry could be something else than a sphere...
  40491. }
  40492. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40493. if (BABYLON.Tags) {
  40494. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40495. }
  40496. scene.pushGeometry(sphere, true);
  40497. return sphere;
  40498. };
  40499. return SphereGeometry;
  40500. }(_PrimitiveGeometry));
  40501. BABYLON.SphereGeometry = SphereGeometry;
  40502. /**
  40503. * Creates a disc geometry
  40504. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40505. */
  40506. var DiscGeometry = /** @class */ (function (_super) {
  40507. __extends(DiscGeometry, _super);
  40508. /**
  40509. * Creates a new disc geometry
  40510. * @param id defines the unique ID of the geometry
  40511. * @param scene defines the hosting scene
  40512. * @param radius defines the radius of the disc
  40513. * @param tessellation defines the tesselation factor to apply to the disc
  40514. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40515. * @param mesh defines the hosting mesh (can be null)
  40516. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40517. */
  40518. function DiscGeometry(id, scene,
  40519. /**
  40520. * Defines the radius of the disc
  40521. */
  40522. radius,
  40523. /**
  40524. * Defines the tesselation factor to apply to the disc
  40525. */
  40526. tessellation, canBeRegenerated, mesh,
  40527. /**
  40528. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40529. */
  40530. side) {
  40531. if (mesh === void 0) { mesh = null; }
  40532. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40533. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40534. _this.radius = radius;
  40535. _this.tessellation = tessellation;
  40536. _this.side = side;
  40537. return _this;
  40538. }
  40539. DiscGeometry.prototype._regenerateVertexData = function () {
  40540. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40541. };
  40542. DiscGeometry.prototype.copy = function (id) {
  40543. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40544. };
  40545. return DiscGeometry;
  40546. }(_PrimitiveGeometry));
  40547. BABYLON.DiscGeometry = DiscGeometry;
  40548. /**
  40549. * Creates a new cylinder geometry
  40550. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40551. */
  40552. var CylinderGeometry = /** @class */ (function (_super) {
  40553. __extends(CylinderGeometry, _super);
  40554. /**
  40555. * Creates a new cylinder geometry
  40556. * @param id defines the unique ID of the geometry
  40557. * @param scene defines the hosting scene
  40558. * @param height defines the height of the cylinder
  40559. * @param diameterTop defines the diameter of the cylinder's top cap
  40560. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40561. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40562. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40563. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40564. * @param mesh defines the hosting mesh (can be null)
  40565. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40566. */
  40567. function CylinderGeometry(id, scene,
  40568. /**
  40569. * Defines the height of the cylinder
  40570. */
  40571. height,
  40572. /**
  40573. * Defines the diameter of the cylinder's top cap
  40574. */
  40575. diameterTop,
  40576. /**
  40577. * Defines the diameter of the cylinder's bottom cap
  40578. */
  40579. diameterBottom,
  40580. /**
  40581. * Defines the tessellation factor to apply to the cylinder
  40582. */
  40583. tessellation,
  40584. /**
  40585. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40586. */
  40587. subdivisions, canBeRegenerated, mesh,
  40588. /**
  40589. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40590. */
  40591. side) {
  40592. if (subdivisions === void 0) { subdivisions = 1; }
  40593. if (mesh === void 0) { mesh = null; }
  40594. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40595. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40596. _this.height = height;
  40597. _this.diameterTop = diameterTop;
  40598. _this.diameterBottom = diameterBottom;
  40599. _this.tessellation = tessellation;
  40600. _this.subdivisions = subdivisions;
  40601. _this.side = side;
  40602. return _this;
  40603. }
  40604. CylinderGeometry.prototype._regenerateVertexData = function () {
  40605. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40606. };
  40607. CylinderGeometry.prototype.copy = function (id) {
  40608. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40609. };
  40610. CylinderGeometry.prototype.serialize = function () {
  40611. var serializationObject = _super.prototype.serialize.call(this);
  40612. serializationObject.height = this.height;
  40613. serializationObject.diameterTop = this.diameterTop;
  40614. serializationObject.diameterBottom = this.diameterBottom;
  40615. serializationObject.tessellation = this.tessellation;
  40616. return serializationObject;
  40617. };
  40618. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40619. if (scene.getGeometryByID(parsedCylinder.id)) {
  40620. return null; // null since geometry could be something else than a cylinder...
  40621. }
  40622. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40623. if (BABYLON.Tags) {
  40624. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40625. }
  40626. scene.pushGeometry(cylinder, true);
  40627. return cylinder;
  40628. };
  40629. return CylinderGeometry;
  40630. }(_PrimitiveGeometry));
  40631. BABYLON.CylinderGeometry = CylinderGeometry;
  40632. /**
  40633. * Creates a new torus geometry
  40634. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40635. */
  40636. var TorusGeometry = /** @class */ (function (_super) {
  40637. __extends(TorusGeometry, _super);
  40638. /**
  40639. * Creates a new torus geometry
  40640. * @param id defines the unique ID of the geometry
  40641. * @param scene defines the hosting scene
  40642. * @param diameter defines the diameter of the torus
  40643. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40644. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40645. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40646. * @param mesh defines the hosting mesh (can be null)
  40647. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40648. */
  40649. function TorusGeometry(id, scene,
  40650. /**
  40651. * Defines the diameter of the torus
  40652. */
  40653. diameter,
  40654. /**
  40655. * Defines the thickness of the torus (ie. internal diameter)
  40656. */
  40657. thickness,
  40658. /**
  40659. * Defines the tesselation factor to apply to the torus
  40660. */
  40661. tessellation, canBeRegenerated, mesh,
  40662. /**
  40663. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40664. */
  40665. side) {
  40666. if (mesh === void 0) { mesh = null; }
  40667. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40668. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40669. _this.diameter = diameter;
  40670. _this.thickness = thickness;
  40671. _this.tessellation = tessellation;
  40672. _this.side = side;
  40673. return _this;
  40674. }
  40675. TorusGeometry.prototype._regenerateVertexData = function () {
  40676. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40677. };
  40678. TorusGeometry.prototype.copy = function (id) {
  40679. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40680. };
  40681. TorusGeometry.prototype.serialize = function () {
  40682. var serializationObject = _super.prototype.serialize.call(this);
  40683. serializationObject.diameter = this.diameter;
  40684. serializationObject.thickness = this.thickness;
  40685. serializationObject.tessellation = this.tessellation;
  40686. return serializationObject;
  40687. };
  40688. TorusGeometry.Parse = function (parsedTorus, scene) {
  40689. if (scene.getGeometryByID(parsedTorus.id)) {
  40690. return null; // null since geometry could be something else than a torus...
  40691. }
  40692. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40693. if (BABYLON.Tags) {
  40694. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40695. }
  40696. scene.pushGeometry(torus, true);
  40697. return torus;
  40698. };
  40699. return TorusGeometry;
  40700. }(_PrimitiveGeometry));
  40701. BABYLON.TorusGeometry = TorusGeometry;
  40702. /**
  40703. * Creates a new ground geometry
  40704. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40705. */
  40706. var GroundGeometry = /** @class */ (function (_super) {
  40707. __extends(GroundGeometry, _super);
  40708. /**
  40709. * Creates a new ground geometry
  40710. * @param id defines the unique ID of the geometry
  40711. * @param scene defines the hosting scene
  40712. * @param width defines the width of the ground
  40713. * @param height defines the height of the ground
  40714. * @param subdivisions defines the subdivisions to apply to the ground
  40715. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40716. * @param mesh defines the hosting mesh (can be null)
  40717. */
  40718. function GroundGeometry(id, scene,
  40719. /**
  40720. * Defines the width of the ground
  40721. */
  40722. width,
  40723. /**
  40724. * Defines the height of the ground
  40725. */
  40726. height,
  40727. /**
  40728. * Defines the subdivisions to apply to the ground
  40729. */
  40730. subdivisions, canBeRegenerated, mesh) {
  40731. if (mesh === void 0) { mesh = null; }
  40732. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40733. _this.width = width;
  40734. _this.height = height;
  40735. _this.subdivisions = subdivisions;
  40736. return _this;
  40737. }
  40738. GroundGeometry.prototype._regenerateVertexData = function () {
  40739. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40740. };
  40741. GroundGeometry.prototype.copy = function (id) {
  40742. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40743. };
  40744. GroundGeometry.prototype.serialize = function () {
  40745. var serializationObject = _super.prototype.serialize.call(this);
  40746. serializationObject.width = this.width;
  40747. serializationObject.height = this.height;
  40748. serializationObject.subdivisions = this.subdivisions;
  40749. return serializationObject;
  40750. };
  40751. GroundGeometry.Parse = function (parsedGround, scene) {
  40752. if (scene.getGeometryByID(parsedGround.id)) {
  40753. return null; // null since geometry could be something else than a ground...
  40754. }
  40755. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40756. if (BABYLON.Tags) {
  40757. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40758. }
  40759. scene.pushGeometry(ground, true);
  40760. return ground;
  40761. };
  40762. return GroundGeometry;
  40763. }(_PrimitiveGeometry));
  40764. BABYLON.GroundGeometry = GroundGeometry;
  40765. /**
  40766. * Creates a tiled ground geometry
  40767. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40768. */
  40769. var TiledGroundGeometry = /** @class */ (function (_super) {
  40770. __extends(TiledGroundGeometry, _super);
  40771. /**
  40772. * Creates a tiled ground geometry
  40773. * @param id defines the unique ID of the geometry
  40774. * @param scene defines the hosting scene
  40775. * @param xmin defines the minimum value on X axis
  40776. * @param zmin defines the minimum value on Z axis
  40777. * @param xmax defines the maximum value on X axis
  40778. * @param zmax defines the maximum value on Z axis
  40779. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40780. * @param precision defines the precision to use when computing the tiles
  40781. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40782. * @param mesh defines the hosting mesh (can be null)
  40783. */
  40784. function TiledGroundGeometry(id, scene,
  40785. /**
  40786. * Defines the minimum value on X axis
  40787. */
  40788. xmin,
  40789. /**
  40790. * Defines the minimum value on Z axis
  40791. */
  40792. zmin,
  40793. /**
  40794. * Defines the maximum value on X axis
  40795. */
  40796. xmax,
  40797. /**
  40798. * Defines the maximum value on Z axis
  40799. */
  40800. zmax,
  40801. /**
  40802. * Defines the subdivisions to apply to the ground
  40803. */
  40804. subdivisions,
  40805. /**
  40806. * Defines the precision to use when computing the tiles
  40807. */
  40808. precision, canBeRegenerated, mesh) {
  40809. if (mesh === void 0) { mesh = null; }
  40810. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40811. _this.xmin = xmin;
  40812. _this.zmin = zmin;
  40813. _this.xmax = xmax;
  40814. _this.zmax = zmax;
  40815. _this.subdivisions = subdivisions;
  40816. _this.precision = precision;
  40817. return _this;
  40818. }
  40819. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40820. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40821. };
  40822. TiledGroundGeometry.prototype.copy = function (id) {
  40823. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40824. };
  40825. return TiledGroundGeometry;
  40826. }(_PrimitiveGeometry));
  40827. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40828. /**
  40829. * Creates a plane geometry
  40830. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40831. */
  40832. var PlaneGeometry = /** @class */ (function (_super) {
  40833. __extends(PlaneGeometry, _super);
  40834. /**
  40835. * Creates a plane geometry
  40836. * @param id defines the unique ID of the geometry
  40837. * @param scene defines the hosting scene
  40838. * @param size defines the size of the plane (width === height)
  40839. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40840. * @param mesh defines the hosting mesh (can be null)
  40841. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40842. */
  40843. function PlaneGeometry(id, scene,
  40844. /**
  40845. * Defines the size of the plane (width === height)
  40846. */
  40847. size, canBeRegenerated, mesh,
  40848. /**
  40849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40850. */
  40851. side) {
  40852. if (mesh === void 0) { mesh = null; }
  40853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40854. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40855. _this.size = size;
  40856. _this.side = side;
  40857. return _this;
  40858. }
  40859. PlaneGeometry.prototype._regenerateVertexData = function () {
  40860. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40861. };
  40862. PlaneGeometry.prototype.copy = function (id) {
  40863. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40864. };
  40865. PlaneGeometry.prototype.serialize = function () {
  40866. var serializationObject = _super.prototype.serialize.call(this);
  40867. serializationObject.size = this.size;
  40868. return serializationObject;
  40869. };
  40870. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40871. if (scene.getGeometryByID(parsedPlane.id)) {
  40872. return null; // null since geometry could be something else than a ground...
  40873. }
  40874. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40875. if (BABYLON.Tags) {
  40876. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40877. }
  40878. scene.pushGeometry(plane, true);
  40879. return plane;
  40880. };
  40881. return PlaneGeometry;
  40882. }(_PrimitiveGeometry));
  40883. BABYLON.PlaneGeometry = PlaneGeometry;
  40884. /**
  40885. * Creates a torus knot geometry
  40886. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40887. */
  40888. var TorusKnotGeometry = /** @class */ (function (_super) {
  40889. __extends(TorusKnotGeometry, _super);
  40890. /**
  40891. * Creates a torus knot geometry
  40892. * @param id defines the unique ID of the geometry
  40893. * @param scene defines the hosting scene
  40894. * @param radius defines the radius of the torus knot
  40895. * @param tube defines the thickness of the torus knot tube
  40896. * @param radialSegments defines the number of radial segments
  40897. * @param tubularSegments defines the number of tubular segments
  40898. * @param p defines the first number of windings
  40899. * @param q defines the second number of windings
  40900. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40901. * @param mesh defines the hosting mesh (can be null)
  40902. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40903. */
  40904. function TorusKnotGeometry(id, scene,
  40905. /**
  40906. * Defines the radius of the torus knot
  40907. */
  40908. radius,
  40909. /**
  40910. * Defines the thickness of the torus knot tube
  40911. */
  40912. tube,
  40913. /**
  40914. * Defines the number of radial segments
  40915. */
  40916. radialSegments,
  40917. /**
  40918. * Defines the number of tubular segments
  40919. */
  40920. tubularSegments,
  40921. /**
  40922. * Defines the first number of windings
  40923. */
  40924. p,
  40925. /**
  40926. * Defines the second number of windings
  40927. */
  40928. q, canBeRegenerated, mesh,
  40929. /**
  40930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40931. */
  40932. side) {
  40933. if (mesh === void 0) { mesh = null; }
  40934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40936. _this.radius = radius;
  40937. _this.tube = tube;
  40938. _this.radialSegments = radialSegments;
  40939. _this.tubularSegments = tubularSegments;
  40940. _this.p = p;
  40941. _this.q = q;
  40942. _this.side = side;
  40943. return _this;
  40944. }
  40945. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40946. 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 });
  40947. };
  40948. TorusKnotGeometry.prototype.copy = function (id) {
  40949. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40950. };
  40951. TorusKnotGeometry.prototype.serialize = function () {
  40952. var serializationObject = _super.prototype.serialize.call(this);
  40953. serializationObject.radius = this.radius;
  40954. serializationObject.tube = this.tube;
  40955. serializationObject.radialSegments = this.radialSegments;
  40956. serializationObject.tubularSegments = this.tubularSegments;
  40957. serializationObject.p = this.p;
  40958. serializationObject.q = this.q;
  40959. return serializationObject;
  40960. };
  40961. ;
  40962. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40963. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40964. return null; // null since geometry could be something else than a ground...
  40965. }
  40966. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40967. if (BABYLON.Tags) {
  40968. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40969. }
  40970. scene.pushGeometry(torusKnot, true);
  40971. return torusKnot;
  40972. };
  40973. return TorusKnotGeometry;
  40974. }(_PrimitiveGeometry));
  40975. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40976. //}
  40977. })(BABYLON || (BABYLON = {}));
  40978. //# sourceMappingURL=babylon.geometry.js.map
  40979. var BABYLON;
  40980. (function (BABYLON) {
  40981. /**
  40982. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40983. */
  40984. var PerformanceMonitor = /** @class */ (function () {
  40985. /**
  40986. * constructor
  40987. * @param frameSampleSize The number of samples required to saturate the sliding window
  40988. */
  40989. function PerformanceMonitor(frameSampleSize) {
  40990. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40991. this._enabled = true;
  40992. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40993. }
  40994. /**
  40995. * Samples current frame
  40996. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40997. */
  40998. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40999. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41000. if (!this._enabled)
  41001. return;
  41002. if (this._lastFrameTimeMs != null) {
  41003. var dt = timeMs - this._lastFrameTimeMs;
  41004. this._rollingFrameTime.add(dt);
  41005. }
  41006. this._lastFrameTimeMs = timeMs;
  41007. };
  41008. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41009. /**
  41010. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41011. * @return Average frame time in milliseconds
  41012. */
  41013. get: function () {
  41014. return this._rollingFrameTime.average;
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41020. /**
  41021. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41022. * @return Frame time variance in milliseconds squared
  41023. */
  41024. get: function () {
  41025. return this._rollingFrameTime.variance;
  41026. },
  41027. enumerable: true,
  41028. configurable: true
  41029. });
  41030. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41031. /**
  41032. * Returns the frame time of the most recent frame
  41033. * @return Frame time in milliseconds
  41034. */
  41035. get: function () {
  41036. return this._rollingFrameTime.history(0);
  41037. },
  41038. enumerable: true,
  41039. configurable: true
  41040. });
  41041. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41042. /**
  41043. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41044. * @return Framerate in frames per second
  41045. */
  41046. get: function () {
  41047. return 1000.0 / this._rollingFrameTime.average;
  41048. },
  41049. enumerable: true,
  41050. configurable: true
  41051. });
  41052. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41053. /**
  41054. * Returns the average framerate in frames per second using the most recent frame time
  41055. * @return Framerate in frames per second
  41056. */
  41057. get: function () {
  41058. var history = this._rollingFrameTime.history(0);
  41059. if (history === 0) {
  41060. return 0;
  41061. }
  41062. return 1000.0 / history;
  41063. },
  41064. enumerable: true,
  41065. configurable: true
  41066. });
  41067. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41068. /**
  41069. * Returns true if enough samples have been taken to completely fill the sliding window
  41070. * @return true if saturated
  41071. */
  41072. get: function () {
  41073. return this._rollingFrameTime.isSaturated();
  41074. },
  41075. enumerable: true,
  41076. configurable: true
  41077. });
  41078. /**
  41079. * Enables contributions to the sliding window sample set
  41080. */
  41081. PerformanceMonitor.prototype.enable = function () {
  41082. this._enabled = true;
  41083. };
  41084. /**
  41085. * Disables contributions to the sliding window sample set
  41086. * Samples will not be interpolated over the disabled period
  41087. */
  41088. PerformanceMonitor.prototype.disable = function () {
  41089. this._enabled = false;
  41090. //clear last sample to avoid interpolating over the disabled period when next enabled
  41091. this._lastFrameTimeMs = null;
  41092. };
  41093. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41094. /**
  41095. * Returns true if sampling is enabled
  41096. * @return true if enabled
  41097. */
  41098. get: function () {
  41099. return this._enabled;
  41100. },
  41101. enumerable: true,
  41102. configurable: true
  41103. });
  41104. /**
  41105. * Resets performance monitor
  41106. */
  41107. PerformanceMonitor.prototype.reset = function () {
  41108. //clear last sample to avoid interpolating over the disabled period when next enabled
  41109. this._lastFrameTimeMs = null;
  41110. //wipe record
  41111. this._rollingFrameTime.reset();
  41112. };
  41113. return PerformanceMonitor;
  41114. }());
  41115. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41116. /**
  41117. * RollingAverage
  41118. *
  41119. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41120. */
  41121. var RollingAverage = /** @class */ (function () {
  41122. /**
  41123. * constructor
  41124. * @param length The number of samples required to saturate the sliding window
  41125. */
  41126. function RollingAverage(length) {
  41127. this._samples = new Array(length);
  41128. this.reset();
  41129. }
  41130. /**
  41131. * Adds a sample to the sample set
  41132. * @param v The sample value
  41133. */
  41134. RollingAverage.prototype.add = function (v) {
  41135. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41136. var delta;
  41137. //we need to check if we've already wrapped round
  41138. if (this.isSaturated()) {
  41139. //remove bottom of stack from mean
  41140. var bottomValue = this._samples[this._pos];
  41141. delta = bottomValue - this.average;
  41142. this.average -= delta / (this._sampleCount - 1);
  41143. this._m2 -= delta * (bottomValue - this.average);
  41144. }
  41145. else {
  41146. this._sampleCount++;
  41147. }
  41148. //add new value to mean
  41149. delta = v - this.average;
  41150. this.average += delta / (this._sampleCount);
  41151. this._m2 += delta * (v - this.average);
  41152. //set the new variance
  41153. this.variance = this._m2 / (this._sampleCount - 1);
  41154. this._samples[this._pos] = v;
  41155. this._pos++;
  41156. this._pos %= this._samples.length; //positive wrap around
  41157. };
  41158. /**
  41159. * Returns previously added values or null if outside of history or outside the sliding window domain
  41160. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41161. * @return Value previously recorded with add() or null if outside of range
  41162. */
  41163. RollingAverage.prototype.history = function (i) {
  41164. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41165. return 0;
  41166. }
  41167. var i0 = this._wrapPosition(this._pos - 1.0);
  41168. return this._samples[this._wrapPosition(i0 - i)];
  41169. };
  41170. /**
  41171. * Returns true if enough samples have been taken to completely fill the sliding window
  41172. * @return true if sample-set saturated
  41173. */
  41174. RollingAverage.prototype.isSaturated = function () {
  41175. return this._sampleCount >= this._samples.length;
  41176. };
  41177. /**
  41178. * Resets the rolling average (equivalent to 0 samples taken so far)
  41179. */
  41180. RollingAverage.prototype.reset = function () {
  41181. this.average = 0;
  41182. this.variance = 0;
  41183. this._sampleCount = 0;
  41184. this._pos = 0;
  41185. this._m2 = 0;
  41186. };
  41187. /**
  41188. * Wraps a value around the sample range boundaries
  41189. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41190. * @return Wrapped position in sample range
  41191. */
  41192. RollingAverage.prototype._wrapPosition = function (i) {
  41193. var max = this._samples.length;
  41194. return ((i % max) + max) % max;
  41195. };
  41196. return RollingAverage;
  41197. }());
  41198. BABYLON.RollingAverage = RollingAverage;
  41199. })(BABYLON || (BABYLON = {}));
  41200. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41201. var BABYLON;
  41202. (function (BABYLON) {
  41203. /**
  41204. * "Static Class" containing the most commonly used helper while dealing with material for
  41205. * rendering purpose.
  41206. *
  41207. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41208. *
  41209. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41210. */
  41211. var MaterialHelper = /** @class */ (function () {
  41212. function MaterialHelper() {
  41213. }
  41214. /**
  41215. * Bind the current view position to an effect.
  41216. * @param effect The effect to be bound
  41217. * @param scene The scene the eyes position is used from
  41218. */
  41219. MaterialHelper.BindEyePosition = function (effect, scene) {
  41220. if (scene._forcedViewPosition) {
  41221. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41222. return;
  41223. }
  41224. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41225. };
  41226. /**
  41227. * Helps preparing the defines values about the UVs in used in the effect.
  41228. * UVs are shared as much as we can accross chanels in the shaders.
  41229. * @param texture The texture we are preparing the UVs for
  41230. * @param defines The defines to update
  41231. * @param key The chanel key "diffuse", "specular"... used in the shader
  41232. */
  41233. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41234. defines._needUVs = true;
  41235. defines[key] = true;
  41236. if (texture.getTextureMatrix().isIdentity(true)) {
  41237. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41238. if (texture.coordinatesIndex === 0) {
  41239. defines["MAINUV1"] = true;
  41240. }
  41241. else {
  41242. defines["MAINUV2"] = true;
  41243. }
  41244. }
  41245. else {
  41246. defines[key + "DIRECTUV"] = 0;
  41247. }
  41248. };
  41249. /**
  41250. * Binds a texture matrix value to its corrsponding uniform
  41251. * @param texture The texture to bind the matrix for
  41252. * @param uniformBuffer The uniform buffer receivin the data
  41253. * @param key The chanel key "diffuse", "specular"... used in the shader
  41254. */
  41255. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41256. var matrix = texture.getTextureMatrix();
  41257. if (!matrix.isIdentity(true)) {
  41258. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41259. }
  41260. };
  41261. /**
  41262. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41263. * @param mesh defines the current mesh
  41264. * @param scene defines the current scene
  41265. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41266. * @param pointsCloud defines if point cloud rendering has to be turned on
  41267. * @param fogEnabled defines if fog has to be turned on
  41268. * @param alphaTest defines if alpha testing has to be turned on
  41269. * @param defines defines the current list of defines
  41270. */
  41271. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41272. if (defines._areMiscDirty) {
  41273. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41274. defines["POINTSIZE"] = pointsCloud;
  41275. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41276. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41277. defines["ALPHATEST"] = alphaTest;
  41278. }
  41279. };
  41280. /**
  41281. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41282. * @param scene defines the current scene
  41283. * @param engine defines the current engine
  41284. * @param defines specifies the list of active defines
  41285. * @param useInstances defines if instances have to be turned on
  41286. * @param useClipPlane defines if clip plane have to be turned on
  41287. */
  41288. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41289. if (useClipPlane === void 0) { useClipPlane = null; }
  41290. var changed = false;
  41291. if (useClipPlane == null) {
  41292. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41293. }
  41294. if (defines["CLIPPLANE"] !== useClipPlane) {
  41295. defines["CLIPPLANE"] = useClipPlane;
  41296. changed = true;
  41297. }
  41298. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41299. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41300. changed = true;
  41301. }
  41302. if (defines["INSTANCES"] !== useInstances) {
  41303. defines["INSTANCES"] = useInstances;
  41304. changed = true;
  41305. }
  41306. if (changed) {
  41307. defines.markAsUnprocessed();
  41308. }
  41309. };
  41310. /**
  41311. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41312. * @param mesh The mesh containing the geometry data we will draw
  41313. * @param defines The defines to update
  41314. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41315. * @param useBones Precise whether bones should be used or not (override mesh info)
  41316. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41317. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41318. * @returns false if defines are considered not dirty and have not been checked
  41319. */
  41320. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41321. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41322. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41323. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41324. return false;
  41325. }
  41326. defines._normals = defines._needNormals;
  41327. defines._uvs = defines._needUVs;
  41328. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41329. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41330. defines["TANGENT"] = true;
  41331. }
  41332. if (defines._needUVs) {
  41333. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41334. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41335. }
  41336. else {
  41337. defines["UV1"] = false;
  41338. defines["UV2"] = false;
  41339. }
  41340. if (useVertexColor) {
  41341. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41342. defines["VERTEXCOLOR"] = hasVertexColors;
  41343. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41344. }
  41345. if (useBones) {
  41346. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41347. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41348. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41349. }
  41350. else {
  41351. defines["NUM_BONE_INFLUENCERS"] = 0;
  41352. defines["BonesPerMesh"] = 0;
  41353. }
  41354. }
  41355. if (useMorphTargets) {
  41356. var manager = mesh.morphTargetManager;
  41357. if (manager) {
  41358. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41359. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41360. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41361. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41362. }
  41363. else {
  41364. defines["MORPHTARGETS_TANGENT"] = false;
  41365. defines["MORPHTARGETS_NORMAL"] = false;
  41366. defines["MORPHTARGETS"] = false;
  41367. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41368. }
  41369. }
  41370. return true;
  41371. };
  41372. /**
  41373. * Prepares the defines related to the light information passed in parameter
  41374. * @param scene The scene we are intending to draw
  41375. * @param mesh The mesh the effect is compiling for
  41376. * @param defines The defines to update
  41377. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41378. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41379. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41380. * @returns true if normals will be required for the rest of the effect
  41381. */
  41382. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41383. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41384. if (disableLighting === void 0) { disableLighting = false; }
  41385. if (!defines._areLightsDirty) {
  41386. return defines._needNormals;
  41387. }
  41388. var lightIndex = 0;
  41389. var needNormals = false;
  41390. var needRebuild = false;
  41391. var lightmapMode = false;
  41392. var shadowEnabled = false;
  41393. var specularEnabled = false;
  41394. if (scene.lightsEnabled && !disableLighting) {
  41395. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41396. var light = _a[_i];
  41397. needNormals = true;
  41398. if (defines["LIGHT" + lightIndex] === undefined) {
  41399. needRebuild = true;
  41400. }
  41401. defines["LIGHT" + lightIndex] = true;
  41402. defines["SPOTLIGHT" + lightIndex] = false;
  41403. defines["HEMILIGHT" + lightIndex] = false;
  41404. defines["POINTLIGHT" + lightIndex] = false;
  41405. defines["DIRLIGHT" + lightIndex] = false;
  41406. var type;
  41407. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41408. type = "SPOTLIGHT" + lightIndex;
  41409. var spotLight = light;
  41410. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41411. }
  41412. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41413. type = "HEMILIGHT" + lightIndex;
  41414. }
  41415. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41416. type = "POINTLIGHT" + lightIndex;
  41417. }
  41418. else {
  41419. type = "DIRLIGHT" + lightIndex;
  41420. }
  41421. defines[type] = true;
  41422. // Specular
  41423. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41424. specularEnabled = true;
  41425. }
  41426. // Shadows
  41427. defines["SHADOW" + lightIndex] = false;
  41428. defines["SHADOWPCF" + lightIndex] = false;
  41429. defines["SHADOWPCSS" + lightIndex] = false;
  41430. defines["SHADOWPOISSON" + lightIndex] = false;
  41431. defines["SHADOWESM" + lightIndex] = false;
  41432. defines["SHADOWCUBE" + lightIndex] = false;
  41433. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41434. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41435. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41436. var shadowGenerator = light.getShadowGenerator();
  41437. if (shadowGenerator) {
  41438. shadowEnabled = true;
  41439. shadowGenerator.prepareDefines(defines, lightIndex);
  41440. }
  41441. }
  41442. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41443. lightmapMode = true;
  41444. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41445. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41446. }
  41447. else {
  41448. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41449. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41450. }
  41451. lightIndex++;
  41452. if (lightIndex === maxSimultaneousLights)
  41453. break;
  41454. }
  41455. }
  41456. defines["SPECULARTERM"] = specularEnabled;
  41457. defines["SHADOWS"] = shadowEnabled;
  41458. // Resetting all other lights if any
  41459. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41460. if (defines["LIGHT" + index] !== undefined) {
  41461. defines["LIGHT" + index] = false;
  41462. defines["HEMILIGHT" + lightIndex] = false;
  41463. defines["POINTLIGHT" + lightIndex] = false;
  41464. defines["DIRLIGHT" + lightIndex] = false;
  41465. defines["SPOTLIGHT" + lightIndex] = false;
  41466. defines["SHADOW" + lightIndex] = false;
  41467. }
  41468. }
  41469. var caps = scene.getEngine().getCaps();
  41470. if (defines["SHADOWFLOAT"] === undefined) {
  41471. needRebuild = true;
  41472. }
  41473. defines["SHADOWFLOAT"] = shadowEnabled &&
  41474. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41475. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41476. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41477. if (needRebuild) {
  41478. defines.rebuild();
  41479. }
  41480. return needNormals;
  41481. };
  41482. /**
  41483. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41484. * that won t be acctive due to defines being turned off.
  41485. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41486. * @param samplersList The samplers list
  41487. * @param defines The defines helping in the list generation
  41488. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41489. */
  41490. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41491. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41492. var uniformsList;
  41493. var uniformBuffersList = null;
  41494. if (uniformsListOrOptions.uniformsNames) {
  41495. var options = uniformsListOrOptions;
  41496. uniformsList = options.uniformsNames;
  41497. uniformBuffersList = options.uniformBuffersNames;
  41498. samplersList = options.samplers;
  41499. defines = options.defines;
  41500. maxSimultaneousLights = options.maxSimultaneousLights;
  41501. }
  41502. else {
  41503. uniformsList = uniformsListOrOptions;
  41504. if (!samplersList) {
  41505. samplersList = [];
  41506. }
  41507. }
  41508. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41509. if (!defines["LIGHT" + lightIndex]) {
  41510. break;
  41511. }
  41512. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41513. if (uniformBuffersList) {
  41514. uniformBuffersList.push("Light" + lightIndex);
  41515. }
  41516. samplersList.push("shadowSampler" + lightIndex);
  41517. samplersList.push("depthSampler" + lightIndex);
  41518. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41519. samplersList.push("projectionLightSampler" + lightIndex);
  41520. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41521. }
  41522. }
  41523. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41524. uniformsList.push("morphTargetInfluences");
  41525. }
  41526. };
  41527. /**
  41528. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41529. * @param defines The defines to update while falling back
  41530. * @param fallbacks The authorized effect fallbacks
  41531. * @param maxSimultaneousLights The maximum number of lights allowed
  41532. * @param rank the current rank of the Effect
  41533. * @returns The newly affected rank
  41534. */
  41535. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41536. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41537. if (rank === void 0) { rank = 0; }
  41538. var lightFallbackRank = 0;
  41539. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41540. if (!defines["LIGHT" + lightIndex]) {
  41541. break;
  41542. }
  41543. if (lightIndex > 0) {
  41544. lightFallbackRank = rank + lightIndex;
  41545. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41546. }
  41547. if (!defines["SHADOWS"]) {
  41548. if (defines["SHADOW" + lightIndex]) {
  41549. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41550. }
  41551. if (defines["SHADOWPCF" + lightIndex]) {
  41552. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41553. }
  41554. if (defines["SHADOWPCSS" + lightIndex]) {
  41555. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41556. }
  41557. if (defines["SHADOWPOISSON" + lightIndex]) {
  41558. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41559. }
  41560. if (defines["SHADOWESM" + lightIndex]) {
  41561. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41562. }
  41563. }
  41564. }
  41565. return lightFallbackRank++;
  41566. };
  41567. /**
  41568. * Prepares the list of attributes required for morph targets according to the effect defines.
  41569. * @param attribs The current list of supported attribs
  41570. * @param mesh The mesh to prepare the morph targets attributes for
  41571. * @param defines The current Defines of the effect
  41572. */
  41573. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41574. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41575. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41576. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41577. var manager = mesh.morphTargetManager;
  41578. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41579. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41580. for (var index = 0; index < influencers; index++) {
  41581. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41582. if (normal) {
  41583. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41584. }
  41585. if (tangent) {
  41586. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41587. }
  41588. if (attribs.length > maxAttributesCount) {
  41589. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41590. }
  41591. }
  41592. }
  41593. };
  41594. /**
  41595. * Prepares the list of attributes required for bones according to the effect defines.
  41596. * @param attribs The current list of supported attribs
  41597. * @param mesh The mesh to prepare the bones attributes for
  41598. * @param defines The current Defines of the effect
  41599. * @param fallbacks The current efffect fallback strategy
  41600. */
  41601. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41602. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41603. fallbacks.addCPUSkinningFallback(0, mesh);
  41604. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41605. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41606. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41607. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41608. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41609. }
  41610. }
  41611. };
  41612. /**
  41613. * Prepares the list of attributes required for instances according to the effect defines.
  41614. * @param attribs The current list of supported attribs
  41615. * @param defines The current Defines of the effect
  41616. */
  41617. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41618. if (defines["INSTANCES"]) {
  41619. attribs.push("world0");
  41620. attribs.push("world1");
  41621. attribs.push("world2");
  41622. attribs.push("world3");
  41623. }
  41624. };
  41625. /**
  41626. * Binds the light shadow information to the effect for the given mesh.
  41627. * @param light The light containing the generator
  41628. * @param scene The scene the lights belongs to
  41629. * @param mesh The mesh we are binding the information to render
  41630. * @param lightIndex The light index in the effect used to render the mesh
  41631. * @param effect The effect we are binding the data to
  41632. */
  41633. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41634. if (light.shadowEnabled && mesh.receiveShadows) {
  41635. var shadowGenerator = light.getShadowGenerator();
  41636. if (shadowGenerator) {
  41637. shadowGenerator.bindShadowLight(lightIndex, effect);
  41638. }
  41639. }
  41640. };
  41641. /**
  41642. * Binds the light information to the effect.
  41643. * @param light The light containing the generator
  41644. * @param effect The effect we are binding the data to
  41645. * @param lightIndex The light index in the effect used to render
  41646. */
  41647. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41648. light.transferToEffect(effect, lightIndex + "");
  41649. };
  41650. /**
  41651. * Binds the lights information from the scene to the effect for the given mesh.
  41652. * @param scene The scene the lights belongs to
  41653. * @param mesh The mesh we are binding the information to render
  41654. * @param effect The effect we are binding the data to
  41655. * @param defines The generated defines for the effect
  41656. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41657. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41658. */
  41659. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41660. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41661. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41662. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41663. for (var i = 0; i < len; i++) {
  41664. var light = mesh._lightSources[i];
  41665. var iAsString = i.toString();
  41666. var scaledIntensity = light.getScaledIntensity();
  41667. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41668. MaterialHelper.BindLightProperties(light, effect, i);
  41669. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41670. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41671. if (defines["SPECULARTERM"]) {
  41672. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41673. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41674. }
  41675. // Shadows
  41676. if (scene.shadowsEnabled) {
  41677. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41678. }
  41679. light._uniformBuffer.update();
  41680. }
  41681. };
  41682. /**
  41683. * Binds the fog information from the scene to the effect for the given mesh.
  41684. * @param scene The scene the lights belongs to
  41685. * @param mesh The mesh we are binding the information to render
  41686. * @param effect The effect we are binding the data to
  41687. */
  41688. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41689. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41690. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41691. effect.setColor3("vFogColor", scene.fogColor);
  41692. }
  41693. };
  41694. /**
  41695. * Binds the bones information from the mesh to the effect.
  41696. * @param mesh The mesh we are binding the information to render
  41697. * @param effect The effect we are binding the data to
  41698. */
  41699. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41700. if (!effect || !mesh) {
  41701. return;
  41702. }
  41703. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41704. mesh.computeBonesUsingShaders = false;
  41705. }
  41706. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41707. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41708. if (matrices) {
  41709. effect.setMatrices("mBones", matrices);
  41710. }
  41711. }
  41712. };
  41713. /**
  41714. * Binds the morph targets information from the mesh to the effect.
  41715. * @param abstractMesh The mesh we are binding the information to render
  41716. * @param effect The effect we are binding the data to
  41717. */
  41718. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41719. var manager = abstractMesh.morphTargetManager;
  41720. if (!abstractMesh || !manager) {
  41721. return;
  41722. }
  41723. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41724. };
  41725. /**
  41726. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41727. * @param defines The generated defines used in the effect
  41728. * @param effect The effect we are binding the data to
  41729. * @param scene The scene we are willing to render with logarithmic scale for
  41730. */
  41731. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41732. if (defines["LOGARITHMICDEPTH"]) {
  41733. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41734. }
  41735. };
  41736. /**
  41737. * Binds the clip plane information from the scene to the effect.
  41738. * @param scene The scene the clip plane information are extracted from
  41739. * @param effect The effect we are binding the data to
  41740. */
  41741. MaterialHelper.BindClipPlane = function (effect, scene) {
  41742. if (scene.clipPlane) {
  41743. var clipPlane = scene.clipPlane;
  41744. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41745. }
  41746. };
  41747. return MaterialHelper;
  41748. }());
  41749. BABYLON.MaterialHelper = MaterialHelper;
  41750. })(BABYLON || (BABYLON = {}));
  41751. //# sourceMappingURL=babylon.materialHelper.js.map
  41752. var BABYLON;
  41753. (function (BABYLON) {
  41754. var PushMaterial = /** @class */ (function (_super) {
  41755. __extends(PushMaterial, _super);
  41756. function PushMaterial(name, scene) {
  41757. var _this = _super.call(this, name, scene) || this;
  41758. _this._normalMatrix = new BABYLON.Matrix();
  41759. _this.storeEffectOnSubMeshes = true;
  41760. return _this;
  41761. }
  41762. PushMaterial.prototype.getEffect = function () {
  41763. return this._activeEffect;
  41764. };
  41765. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41766. if (!mesh) {
  41767. return false;
  41768. }
  41769. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41770. return true;
  41771. }
  41772. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41773. };
  41774. /**
  41775. * Binds the given world matrix to the active effect
  41776. *
  41777. * @param world the matrix to bind
  41778. */
  41779. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41780. this._activeEffect.setMatrix("world", world);
  41781. };
  41782. /**
  41783. * Binds the given normal matrix to the active effect
  41784. *
  41785. * @param normalMatrix the matrix to bind
  41786. */
  41787. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41788. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41789. };
  41790. PushMaterial.prototype.bind = function (world, mesh) {
  41791. if (!mesh) {
  41792. return;
  41793. }
  41794. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41795. };
  41796. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41797. if (effect === void 0) { effect = null; }
  41798. _super.prototype._afterBind.call(this, mesh);
  41799. this.getScene()._cachedEffect = effect;
  41800. };
  41801. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41802. if (visibility === void 0) { visibility = 1; }
  41803. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41804. };
  41805. return PushMaterial;
  41806. }(BABYLON.Material));
  41807. BABYLON.PushMaterial = PushMaterial;
  41808. })(BABYLON || (BABYLON = {}));
  41809. //# sourceMappingURL=babylon.pushMaterial.js.map
  41810. var BABYLON;
  41811. (function (BABYLON) {
  41812. /** @hidden */
  41813. var StandardMaterialDefines = /** @class */ (function (_super) {
  41814. __extends(StandardMaterialDefines, _super);
  41815. function StandardMaterialDefines() {
  41816. var _this = _super.call(this) || this;
  41817. _this.MAINUV1 = false;
  41818. _this.MAINUV2 = false;
  41819. _this.DIFFUSE = false;
  41820. _this.DIFFUSEDIRECTUV = 0;
  41821. _this.AMBIENT = false;
  41822. _this.AMBIENTDIRECTUV = 0;
  41823. _this.OPACITY = false;
  41824. _this.OPACITYDIRECTUV = 0;
  41825. _this.OPACITYRGB = false;
  41826. _this.REFLECTION = false;
  41827. _this.EMISSIVE = false;
  41828. _this.EMISSIVEDIRECTUV = 0;
  41829. _this.SPECULAR = false;
  41830. _this.SPECULARDIRECTUV = 0;
  41831. _this.BUMP = false;
  41832. _this.BUMPDIRECTUV = 0;
  41833. _this.PARALLAX = false;
  41834. _this.PARALLAXOCCLUSION = false;
  41835. _this.SPECULAROVERALPHA = false;
  41836. _this.CLIPPLANE = false;
  41837. _this.ALPHATEST = false;
  41838. _this.DEPTHPREPASS = false;
  41839. _this.ALPHAFROMDIFFUSE = false;
  41840. _this.POINTSIZE = false;
  41841. _this.FOG = false;
  41842. _this.SPECULARTERM = false;
  41843. _this.DIFFUSEFRESNEL = false;
  41844. _this.OPACITYFRESNEL = false;
  41845. _this.REFLECTIONFRESNEL = false;
  41846. _this.REFRACTIONFRESNEL = false;
  41847. _this.EMISSIVEFRESNEL = false;
  41848. _this.FRESNEL = false;
  41849. _this.NORMAL = false;
  41850. _this.UV1 = false;
  41851. _this.UV2 = false;
  41852. _this.VERTEXCOLOR = false;
  41853. _this.VERTEXALPHA = false;
  41854. _this.NUM_BONE_INFLUENCERS = 0;
  41855. _this.BonesPerMesh = 0;
  41856. _this.INSTANCES = false;
  41857. _this.GLOSSINESS = false;
  41858. _this.ROUGHNESS = false;
  41859. _this.EMISSIVEASILLUMINATION = false;
  41860. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41861. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41862. _this.LIGHTMAP = false;
  41863. _this.LIGHTMAPDIRECTUV = 0;
  41864. _this.OBJECTSPACE_NORMALMAP = false;
  41865. _this.USELIGHTMAPASSHADOWMAP = false;
  41866. _this.REFLECTIONMAP_3D = false;
  41867. _this.REFLECTIONMAP_SPHERICAL = false;
  41868. _this.REFLECTIONMAP_PLANAR = false;
  41869. _this.REFLECTIONMAP_CUBIC = false;
  41870. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41871. _this.REFLECTIONMAP_PROJECTION = false;
  41872. _this.REFLECTIONMAP_SKYBOX = false;
  41873. _this.REFLECTIONMAP_EXPLICIT = false;
  41874. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41875. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41876. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41877. _this.INVERTCUBICMAP = false;
  41878. _this.LOGARITHMICDEPTH = false;
  41879. _this.REFRACTION = false;
  41880. _this.REFRACTIONMAP_3D = false;
  41881. _this.REFLECTIONOVERALPHA = false;
  41882. _this.TWOSIDEDLIGHTING = false;
  41883. _this.SHADOWFLOAT = false;
  41884. _this.MORPHTARGETS = false;
  41885. _this.MORPHTARGETS_NORMAL = false;
  41886. _this.MORPHTARGETS_TANGENT = false;
  41887. _this.NUM_MORPH_INFLUENCERS = 0;
  41888. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41889. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41890. _this.IMAGEPROCESSING = false;
  41891. _this.VIGNETTE = false;
  41892. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41893. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41894. _this.TONEMAPPING = false;
  41895. _this.CONTRAST = false;
  41896. _this.COLORCURVES = false;
  41897. _this.COLORGRADING = false;
  41898. _this.COLORGRADING3D = false;
  41899. _this.SAMPLER3DGREENDEPTH = false;
  41900. _this.SAMPLER3DBGRMAP = false;
  41901. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41902. /**
  41903. * If the reflection texture on this material is in linear color space
  41904. * @hidden
  41905. */
  41906. _this.IS_REFLECTION_LINEAR = false;
  41907. /**
  41908. * If the refraction texture on this material is in linear color space
  41909. * @hidden
  41910. */
  41911. _this.IS_REFRACTION_LINEAR = false;
  41912. _this.EXPOSURE = false;
  41913. _this.rebuild();
  41914. return _this;
  41915. }
  41916. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41917. var modes = [
  41918. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41919. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41920. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41921. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41922. ];
  41923. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41924. var mode = modes_1[_i];
  41925. this[mode] = (mode === modeToEnable);
  41926. }
  41927. };
  41928. return StandardMaterialDefines;
  41929. }(BABYLON.MaterialDefines));
  41930. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41931. var StandardMaterial = /** @class */ (function (_super) {
  41932. __extends(StandardMaterial, _super);
  41933. function StandardMaterial(name, scene) {
  41934. var _this = _super.call(this, name, scene) || this;
  41935. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41936. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41937. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41938. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41939. _this.specularPower = 64;
  41940. _this._useAlphaFromDiffuseTexture = false;
  41941. _this._useEmissiveAsIllumination = false;
  41942. _this._linkEmissiveWithDiffuse = false;
  41943. _this._useSpecularOverAlpha = false;
  41944. _this._useReflectionOverAlpha = false;
  41945. _this._disableLighting = false;
  41946. _this._useObjectSpaceNormalMap = false;
  41947. _this._useParallax = false;
  41948. _this._useParallaxOcclusion = false;
  41949. _this.parallaxScaleBias = 0.05;
  41950. _this._roughness = 0;
  41951. _this.indexOfRefraction = 0.98;
  41952. _this.invertRefractionY = true;
  41953. /**
  41954. * Defines the alpha limits in alpha test mode
  41955. */
  41956. _this.alphaCutOff = 0.4;
  41957. _this._useLightmapAsShadowmap = false;
  41958. _this._useReflectionFresnelFromSpecular = false;
  41959. _this._useGlossinessFromSpecularMapAlpha = false;
  41960. _this._maxSimultaneousLights = 4;
  41961. /**
  41962. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41963. */
  41964. _this._invertNormalMapX = false;
  41965. /**
  41966. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41967. */
  41968. _this._invertNormalMapY = false;
  41969. /**
  41970. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41971. */
  41972. _this._twoSidedLighting = false;
  41973. _this._renderTargets = new BABYLON.SmartArray(16);
  41974. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41975. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41976. // Setup the default processing configuration to the scene.
  41977. _this._attachImageProcessingConfiguration(null);
  41978. _this.getRenderTargetTextures = function () {
  41979. _this._renderTargets.reset();
  41980. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41981. _this._renderTargets.push(_this._reflectionTexture);
  41982. }
  41983. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41984. _this._renderTargets.push(_this._refractionTexture);
  41985. }
  41986. return _this._renderTargets;
  41987. };
  41988. return _this;
  41989. }
  41990. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41991. /**
  41992. * Gets the image processing configuration used either in this material.
  41993. */
  41994. get: function () {
  41995. return this._imageProcessingConfiguration;
  41996. },
  41997. /**
  41998. * Sets the Default image processing configuration used either in the this material.
  41999. *
  42000. * If sets to null, the scene one is in use.
  42001. */
  42002. set: function (value) {
  42003. this._attachImageProcessingConfiguration(value);
  42004. // Ensure the effect will be rebuilt.
  42005. this._markAllSubMeshesAsTexturesDirty();
  42006. },
  42007. enumerable: true,
  42008. configurable: true
  42009. });
  42010. /**
  42011. * Attaches a new image processing configuration to the Standard Material.
  42012. * @param configuration
  42013. */
  42014. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42015. var _this = this;
  42016. if (configuration === this._imageProcessingConfiguration) {
  42017. return;
  42018. }
  42019. // Detaches observer.
  42020. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42021. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42022. }
  42023. // Pick the scene configuration if needed.
  42024. if (!configuration) {
  42025. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42026. }
  42027. else {
  42028. this._imageProcessingConfiguration = configuration;
  42029. }
  42030. // Attaches observer.
  42031. if (this._imageProcessingConfiguration) {
  42032. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42033. _this._markAllSubMeshesAsImageProcessingDirty();
  42034. });
  42035. }
  42036. };
  42037. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42038. /**
  42039. * Gets wether the color curves effect is enabled.
  42040. */
  42041. get: function () {
  42042. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42043. },
  42044. /**
  42045. * Sets wether the color curves effect is enabled.
  42046. */
  42047. set: function (value) {
  42048. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42054. /**
  42055. * Gets wether the color grading effect is enabled.
  42056. */
  42057. get: function () {
  42058. return this.imageProcessingConfiguration.colorGradingEnabled;
  42059. },
  42060. /**
  42061. * Gets wether the color grading effect is enabled.
  42062. */
  42063. set: function (value) {
  42064. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42065. },
  42066. enumerable: true,
  42067. configurable: true
  42068. });
  42069. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42070. /**
  42071. * Gets wether tonemapping is enabled or not.
  42072. */
  42073. get: function () {
  42074. return this._imageProcessingConfiguration.toneMappingEnabled;
  42075. },
  42076. /**
  42077. * Sets wether tonemapping is enabled or not
  42078. */
  42079. set: function (value) {
  42080. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42081. },
  42082. enumerable: true,
  42083. configurable: true
  42084. });
  42085. ;
  42086. ;
  42087. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42088. /**
  42089. * The camera exposure used on this material.
  42090. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42091. * This corresponds to a photographic exposure.
  42092. */
  42093. get: function () {
  42094. return this._imageProcessingConfiguration.exposure;
  42095. },
  42096. /**
  42097. * The camera exposure used on this material.
  42098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42099. * This corresponds to a photographic exposure.
  42100. */
  42101. set: function (value) {
  42102. this._imageProcessingConfiguration.exposure = value;
  42103. },
  42104. enumerable: true,
  42105. configurable: true
  42106. });
  42107. ;
  42108. ;
  42109. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42110. /**
  42111. * Gets The camera contrast used on this material.
  42112. */
  42113. get: function () {
  42114. return this._imageProcessingConfiguration.contrast;
  42115. },
  42116. /**
  42117. * Sets The camera contrast used on this material.
  42118. */
  42119. set: function (value) {
  42120. this._imageProcessingConfiguration.contrast = value;
  42121. },
  42122. enumerable: true,
  42123. configurable: true
  42124. });
  42125. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42126. /**
  42127. * Gets the Color Grading 2D Lookup Texture.
  42128. */
  42129. get: function () {
  42130. return this._imageProcessingConfiguration.colorGradingTexture;
  42131. },
  42132. /**
  42133. * Sets the Color Grading 2D Lookup Texture.
  42134. */
  42135. set: function (value) {
  42136. this._imageProcessingConfiguration.colorGradingTexture = value;
  42137. },
  42138. enumerable: true,
  42139. configurable: true
  42140. });
  42141. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42142. /**
  42143. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42144. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42145. * 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;
  42146. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42147. */
  42148. get: function () {
  42149. return this._imageProcessingConfiguration.colorCurves;
  42150. },
  42151. /**
  42152. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42153. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42154. * 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;
  42155. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42156. */
  42157. set: function (value) {
  42158. this._imageProcessingConfiguration.colorCurves = value;
  42159. },
  42160. enumerable: true,
  42161. configurable: true
  42162. });
  42163. StandardMaterial.prototype.getClassName = function () {
  42164. return "StandardMaterial";
  42165. };
  42166. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42167. get: function () {
  42168. return this._useLogarithmicDepth;
  42169. },
  42170. set: function (value) {
  42171. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42172. this._markAllSubMeshesAsMiscDirty();
  42173. },
  42174. enumerable: true,
  42175. configurable: true
  42176. });
  42177. StandardMaterial.prototype.needAlphaBlending = function () {
  42178. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42179. };
  42180. StandardMaterial.prototype.needAlphaTesting = function () {
  42181. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42182. };
  42183. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42184. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42185. };
  42186. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42187. return this._diffuseTexture;
  42188. };
  42189. /**
  42190. * Child classes can use it to update shaders
  42191. */
  42192. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42193. if (useInstances === void 0) { useInstances = false; }
  42194. if (subMesh.effect && this.isFrozen) {
  42195. if (this._wasPreviouslyReady && subMesh.effect) {
  42196. return true;
  42197. }
  42198. }
  42199. if (!subMesh._materialDefines) {
  42200. subMesh._materialDefines = new StandardMaterialDefines();
  42201. }
  42202. var scene = this.getScene();
  42203. var defines = subMesh._materialDefines;
  42204. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42205. if (defines._renderId === scene.getRenderId()) {
  42206. return true;
  42207. }
  42208. }
  42209. var engine = scene.getEngine();
  42210. // Lights
  42211. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42212. // Textures
  42213. if (defines._areTexturesDirty) {
  42214. defines._needUVs = false;
  42215. defines.MAINUV1 = false;
  42216. defines.MAINUV2 = false;
  42217. if (scene.texturesEnabled) {
  42218. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42219. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42220. return false;
  42221. }
  42222. else {
  42223. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42224. }
  42225. }
  42226. else {
  42227. defines.DIFFUSE = false;
  42228. }
  42229. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42230. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42231. return false;
  42232. }
  42233. else {
  42234. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42235. }
  42236. }
  42237. else {
  42238. defines.AMBIENT = false;
  42239. }
  42240. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42241. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42242. return false;
  42243. }
  42244. else {
  42245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42246. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42247. }
  42248. }
  42249. else {
  42250. defines.OPACITY = false;
  42251. }
  42252. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42253. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42254. return false;
  42255. }
  42256. else {
  42257. defines._needNormals = true;
  42258. defines.REFLECTION = true;
  42259. defines.ROUGHNESS = (this._roughness > 0);
  42260. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42261. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42262. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42263. switch (this._reflectionTexture.coordinatesMode) {
  42264. case BABYLON.Texture.EXPLICIT_MODE:
  42265. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42266. break;
  42267. case BABYLON.Texture.PLANAR_MODE:
  42268. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42269. break;
  42270. case BABYLON.Texture.PROJECTION_MODE:
  42271. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42272. break;
  42273. case BABYLON.Texture.SKYBOX_MODE:
  42274. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42275. break;
  42276. case BABYLON.Texture.SPHERICAL_MODE:
  42277. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42278. break;
  42279. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42280. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42281. break;
  42282. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42283. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42284. break;
  42285. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42286. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42287. break;
  42288. case BABYLON.Texture.CUBIC_MODE:
  42289. case BABYLON.Texture.INVCUBIC_MODE:
  42290. default:
  42291. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42292. break;
  42293. }
  42294. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42295. }
  42296. }
  42297. else {
  42298. defines.REFLECTION = false;
  42299. }
  42300. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42301. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42302. return false;
  42303. }
  42304. else {
  42305. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42306. }
  42307. }
  42308. else {
  42309. defines.EMISSIVE = false;
  42310. }
  42311. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42312. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42313. return false;
  42314. }
  42315. else {
  42316. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42317. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42318. }
  42319. }
  42320. else {
  42321. defines.LIGHTMAP = false;
  42322. }
  42323. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42324. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42325. return false;
  42326. }
  42327. else {
  42328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42329. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42330. }
  42331. }
  42332. else {
  42333. defines.SPECULAR = false;
  42334. }
  42335. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42336. // Bump texure can not be not blocking.
  42337. if (!this._bumpTexture.isReady()) {
  42338. return false;
  42339. }
  42340. else {
  42341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42342. defines.PARALLAX = this._useParallax;
  42343. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42344. }
  42345. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42346. }
  42347. else {
  42348. defines.BUMP = false;
  42349. }
  42350. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42351. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42352. return false;
  42353. }
  42354. else {
  42355. defines._needUVs = true;
  42356. defines.REFRACTION = true;
  42357. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42358. }
  42359. }
  42360. else {
  42361. defines.REFRACTION = false;
  42362. }
  42363. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42364. }
  42365. else {
  42366. defines.DIFFUSE = false;
  42367. defines.AMBIENT = false;
  42368. defines.OPACITY = false;
  42369. defines.REFLECTION = false;
  42370. defines.EMISSIVE = false;
  42371. defines.LIGHTMAP = false;
  42372. defines.BUMP = false;
  42373. defines.REFRACTION = false;
  42374. }
  42375. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42376. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42377. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42378. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42379. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42380. }
  42381. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42382. if (!this._imageProcessingConfiguration.isReady()) {
  42383. return false;
  42384. }
  42385. this._imageProcessingConfiguration.prepareDefines(defines);
  42386. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42387. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42388. }
  42389. if (defines._areFresnelDirty) {
  42390. if (StandardMaterial.FresnelEnabled) {
  42391. // Fresnel
  42392. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42393. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42394. this._reflectionFresnelParameters) {
  42395. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42396. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42397. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42398. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42399. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42400. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42401. defines._needNormals = true;
  42402. defines.FRESNEL = true;
  42403. }
  42404. }
  42405. else {
  42406. defines.FRESNEL = false;
  42407. }
  42408. }
  42409. // Misc.
  42410. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42411. // Attribs
  42412. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42413. // Values that need to be evaluated on every frame
  42414. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42415. // Get correct effect
  42416. if (defines.isDirty) {
  42417. defines.markAsProcessed();
  42418. scene.resetCachedMaterial();
  42419. // Fallbacks
  42420. var fallbacks = new BABYLON.EffectFallbacks();
  42421. if (defines.REFLECTION) {
  42422. fallbacks.addFallback(0, "REFLECTION");
  42423. }
  42424. if (defines.SPECULAR) {
  42425. fallbacks.addFallback(0, "SPECULAR");
  42426. }
  42427. if (defines.BUMP) {
  42428. fallbacks.addFallback(0, "BUMP");
  42429. }
  42430. if (defines.PARALLAX) {
  42431. fallbacks.addFallback(1, "PARALLAX");
  42432. }
  42433. if (defines.PARALLAXOCCLUSION) {
  42434. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42435. }
  42436. if (defines.SPECULAROVERALPHA) {
  42437. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42438. }
  42439. if (defines.FOG) {
  42440. fallbacks.addFallback(1, "FOG");
  42441. }
  42442. if (defines.POINTSIZE) {
  42443. fallbacks.addFallback(0, "POINTSIZE");
  42444. }
  42445. if (defines.LOGARITHMICDEPTH) {
  42446. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42447. }
  42448. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42449. if (defines.SPECULARTERM) {
  42450. fallbacks.addFallback(0, "SPECULARTERM");
  42451. }
  42452. if (defines.DIFFUSEFRESNEL) {
  42453. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42454. }
  42455. if (defines.OPACITYFRESNEL) {
  42456. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42457. }
  42458. if (defines.REFLECTIONFRESNEL) {
  42459. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42460. }
  42461. if (defines.EMISSIVEFRESNEL) {
  42462. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42463. }
  42464. if (defines.FRESNEL) {
  42465. fallbacks.addFallback(4, "FRESNEL");
  42466. }
  42467. //Attributes
  42468. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42469. if (defines.NORMAL) {
  42470. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42471. }
  42472. if (defines.UV1) {
  42473. attribs.push(BABYLON.VertexBuffer.UVKind);
  42474. }
  42475. if (defines.UV2) {
  42476. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42477. }
  42478. if (defines.VERTEXCOLOR) {
  42479. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42480. }
  42481. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42482. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42483. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42484. var shaderName = "default";
  42485. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42486. "vFogInfos", "vFogColor", "pointSize",
  42487. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42488. "mBones",
  42489. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42490. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42491. "vReflectionPosition", "vReflectionSize",
  42492. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42493. ];
  42494. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42495. var uniformBuffers = ["Material", "Scene"];
  42496. if (BABYLON.ImageProcessingConfiguration) {
  42497. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42498. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42499. }
  42500. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42501. uniformsNames: uniforms,
  42502. uniformBuffersNames: uniformBuffers,
  42503. samplers: samplers,
  42504. defines: defines,
  42505. maxSimultaneousLights: this._maxSimultaneousLights
  42506. });
  42507. if (this.customShaderNameResolve) {
  42508. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42509. }
  42510. var join = defines.toString();
  42511. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42512. attributes: attribs,
  42513. uniformsNames: uniforms,
  42514. uniformBuffersNames: uniformBuffers,
  42515. samplers: samplers,
  42516. defines: join,
  42517. fallbacks: fallbacks,
  42518. onCompiled: this.onCompiled,
  42519. onError: this.onError,
  42520. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42521. }, engine), defines);
  42522. this.buildUniformLayout();
  42523. }
  42524. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42525. return false;
  42526. }
  42527. defines._renderId = scene.getRenderId();
  42528. this._wasPreviouslyReady = true;
  42529. return true;
  42530. };
  42531. StandardMaterial.prototype.buildUniformLayout = function () {
  42532. // Order is important !
  42533. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42534. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42535. this._uniformBuffer.addUniform("opacityParts", 4);
  42536. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42537. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42538. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42539. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42540. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42541. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42542. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42543. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42544. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42545. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42546. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42547. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42548. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42549. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42550. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42551. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42552. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42553. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42554. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42555. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42556. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42557. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42558. this._uniformBuffer.addUniform("specularMatrix", 16);
  42559. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42560. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42561. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42562. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42563. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42564. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42565. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42566. this._uniformBuffer.addUniform("pointSize", 1);
  42567. this._uniformBuffer.create();
  42568. };
  42569. StandardMaterial.prototype.unbind = function () {
  42570. if (this._activeEffect) {
  42571. var needFlag = false;
  42572. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42573. this._activeEffect.setTexture("reflection2DSampler", null);
  42574. needFlag = true;
  42575. }
  42576. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42577. this._activeEffect.setTexture("refraction2DSampler", null);
  42578. needFlag = true;
  42579. }
  42580. if (needFlag) {
  42581. this._markAllSubMeshesAsTexturesDirty();
  42582. }
  42583. }
  42584. _super.prototype.unbind.call(this);
  42585. };
  42586. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42587. var scene = this.getScene();
  42588. var defines = subMesh._materialDefines;
  42589. if (!defines) {
  42590. return;
  42591. }
  42592. var effect = subMesh.effect;
  42593. if (!effect) {
  42594. return;
  42595. }
  42596. this._activeEffect = effect;
  42597. // Matrices
  42598. this.bindOnlyWorldMatrix(world);
  42599. // Normal Matrix
  42600. if (defines.OBJECTSPACE_NORMALMAP) {
  42601. world.toNormalMatrix(this._normalMatrix);
  42602. this.bindOnlyNormalMatrix(this._normalMatrix);
  42603. }
  42604. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42605. // Bones
  42606. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42607. if (mustRebind) {
  42608. this._uniformBuffer.bindToEffect(effect, "Material");
  42609. this.bindViewProjection(effect);
  42610. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42611. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42612. // Fresnel
  42613. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42614. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42615. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42616. }
  42617. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42618. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42619. }
  42620. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42621. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42622. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42623. }
  42624. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42625. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42626. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42627. }
  42628. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42629. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42630. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42631. }
  42632. }
  42633. // Textures
  42634. if (scene.texturesEnabled) {
  42635. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42636. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42637. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42638. if (this._diffuseTexture.hasAlpha) {
  42639. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42640. }
  42641. }
  42642. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42643. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42644. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42645. }
  42646. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42647. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42648. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42649. }
  42650. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42651. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42652. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42653. if (this._reflectionTexture.boundingBoxSize) {
  42654. var cubeTexture = this._reflectionTexture;
  42655. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42656. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42657. }
  42658. }
  42659. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42660. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42661. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42662. }
  42663. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42664. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42665. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42666. }
  42667. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42668. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42669. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42670. }
  42671. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42672. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42673. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42674. if (scene._mirroredCameraPosition) {
  42675. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42676. }
  42677. else {
  42678. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42679. }
  42680. }
  42681. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42682. var depth = 1.0;
  42683. if (!this._refractionTexture.isCube) {
  42684. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42685. if (this._refractionTexture.depth) {
  42686. depth = this._refractionTexture.depth;
  42687. }
  42688. }
  42689. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42690. }
  42691. }
  42692. // Point size
  42693. if (this.pointsCloud) {
  42694. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42695. }
  42696. if (defines.SPECULARTERM) {
  42697. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42698. }
  42699. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42700. // Diffuse
  42701. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42702. }
  42703. // Textures
  42704. if (scene.texturesEnabled) {
  42705. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42706. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42707. }
  42708. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42709. effect.setTexture("ambientSampler", this._ambientTexture);
  42710. }
  42711. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42712. effect.setTexture("opacitySampler", this._opacityTexture);
  42713. }
  42714. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42715. if (this._reflectionTexture.isCube) {
  42716. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42717. }
  42718. else {
  42719. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42720. }
  42721. }
  42722. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42723. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42724. }
  42725. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42726. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42727. }
  42728. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42729. effect.setTexture("specularSampler", this._specularTexture);
  42730. }
  42731. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42732. effect.setTexture("bumpSampler", this._bumpTexture);
  42733. }
  42734. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42735. var depth = 1.0;
  42736. if (this._refractionTexture.isCube) {
  42737. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42738. }
  42739. else {
  42740. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42741. }
  42742. }
  42743. }
  42744. // Clip plane
  42745. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42746. // Colors
  42747. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42748. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42749. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42750. }
  42751. if (mustRebind || !this.isFrozen) {
  42752. // Lights
  42753. if (scene.lightsEnabled && !this._disableLighting) {
  42754. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42755. }
  42756. // View
  42757. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42758. this.bindView(effect);
  42759. }
  42760. // Fog
  42761. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42762. // Morph targets
  42763. if (defines.NUM_MORPH_INFLUENCERS) {
  42764. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42765. }
  42766. // Log. depth
  42767. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42768. // image processing
  42769. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42770. this._imageProcessingConfiguration.bind(this._activeEffect);
  42771. }
  42772. }
  42773. this._uniformBuffer.update();
  42774. this._afterBind(mesh, this._activeEffect);
  42775. };
  42776. StandardMaterial.prototype.getAnimatables = function () {
  42777. var results = [];
  42778. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42779. results.push(this._diffuseTexture);
  42780. }
  42781. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42782. results.push(this._ambientTexture);
  42783. }
  42784. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42785. results.push(this._opacityTexture);
  42786. }
  42787. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42788. results.push(this._reflectionTexture);
  42789. }
  42790. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42791. results.push(this._emissiveTexture);
  42792. }
  42793. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42794. results.push(this._specularTexture);
  42795. }
  42796. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42797. results.push(this._bumpTexture);
  42798. }
  42799. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42800. results.push(this._lightmapTexture);
  42801. }
  42802. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42803. results.push(this._refractionTexture);
  42804. }
  42805. return results;
  42806. };
  42807. StandardMaterial.prototype.getActiveTextures = function () {
  42808. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42809. if (this._diffuseTexture) {
  42810. activeTextures.push(this._diffuseTexture);
  42811. }
  42812. if (this._ambientTexture) {
  42813. activeTextures.push(this._ambientTexture);
  42814. }
  42815. if (this._opacityTexture) {
  42816. activeTextures.push(this._opacityTexture);
  42817. }
  42818. if (this._reflectionTexture) {
  42819. activeTextures.push(this._reflectionTexture);
  42820. }
  42821. if (this._emissiveTexture) {
  42822. activeTextures.push(this._emissiveTexture);
  42823. }
  42824. if (this._specularTexture) {
  42825. activeTextures.push(this._specularTexture);
  42826. }
  42827. if (this._bumpTexture) {
  42828. activeTextures.push(this._bumpTexture);
  42829. }
  42830. if (this._lightmapTexture) {
  42831. activeTextures.push(this._lightmapTexture);
  42832. }
  42833. if (this._refractionTexture) {
  42834. activeTextures.push(this._refractionTexture);
  42835. }
  42836. return activeTextures;
  42837. };
  42838. StandardMaterial.prototype.hasTexture = function (texture) {
  42839. if (_super.prototype.hasTexture.call(this, texture)) {
  42840. return true;
  42841. }
  42842. if (this._diffuseTexture === texture) {
  42843. return true;
  42844. }
  42845. if (this._ambientTexture === texture) {
  42846. return true;
  42847. }
  42848. if (this._opacityTexture === texture) {
  42849. return true;
  42850. }
  42851. if (this._reflectionTexture === texture) {
  42852. return true;
  42853. }
  42854. if (this._emissiveTexture === texture) {
  42855. return true;
  42856. }
  42857. if (this._specularTexture === texture) {
  42858. return true;
  42859. }
  42860. if (this._bumpTexture === texture) {
  42861. return true;
  42862. }
  42863. if (this._lightmapTexture === texture) {
  42864. return true;
  42865. }
  42866. if (this._refractionTexture === texture) {
  42867. return true;
  42868. }
  42869. return false;
  42870. };
  42871. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42872. if (forceDisposeTextures) {
  42873. if (this._diffuseTexture) {
  42874. this._diffuseTexture.dispose();
  42875. }
  42876. if (this._ambientTexture) {
  42877. this._ambientTexture.dispose();
  42878. }
  42879. if (this._opacityTexture) {
  42880. this._opacityTexture.dispose();
  42881. }
  42882. if (this._reflectionTexture) {
  42883. this._reflectionTexture.dispose();
  42884. }
  42885. if (this._emissiveTexture) {
  42886. this._emissiveTexture.dispose();
  42887. }
  42888. if (this._specularTexture) {
  42889. this._specularTexture.dispose();
  42890. }
  42891. if (this._bumpTexture) {
  42892. this._bumpTexture.dispose();
  42893. }
  42894. if (this._lightmapTexture) {
  42895. this._lightmapTexture.dispose();
  42896. }
  42897. if (this._refractionTexture) {
  42898. this._refractionTexture.dispose();
  42899. }
  42900. }
  42901. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42902. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42903. }
  42904. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42905. };
  42906. StandardMaterial.prototype.clone = function (name) {
  42907. var _this = this;
  42908. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42909. result.name = name;
  42910. result.id = name;
  42911. return result;
  42912. };
  42913. StandardMaterial.prototype.serialize = function () {
  42914. return BABYLON.SerializationHelper.Serialize(this);
  42915. };
  42916. // Statics
  42917. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42918. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42919. };
  42920. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42921. get: function () {
  42922. return StandardMaterial._DiffuseTextureEnabled;
  42923. },
  42924. set: function (value) {
  42925. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42926. return;
  42927. }
  42928. StandardMaterial._DiffuseTextureEnabled = value;
  42929. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42930. },
  42931. enumerable: true,
  42932. configurable: true
  42933. });
  42934. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42935. get: function () {
  42936. return StandardMaterial._AmbientTextureEnabled;
  42937. },
  42938. set: function (value) {
  42939. if (StandardMaterial._AmbientTextureEnabled === value) {
  42940. return;
  42941. }
  42942. StandardMaterial._AmbientTextureEnabled = value;
  42943. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42944. },
  42945. enumerable: true,
  42946. configurable: true
  42947. });
  42948. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42949. get: function () {
  42950. return StandardMaterial._OpacityTextureEnabled;
  42951. },
  42952. set: function (value) {
  42953. if (StandardMaterial._OpacityTextureEnabled === value) {
  42954. return;
  42955. }
  42956. StandardMaterial._OpacityTextureEnabled = value;
  42957. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42958. },
  42959. enumerable: true,
  42960. configurable: true
  42961. });
  42962. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42963. get: function () {
  42964. return StandardMaterial._ReflectionTextureEnabled;
  42965. },
  42966. set: function (value) {
  42967. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42968. return;
  42969. }
  42970. StandardMaterial._ReflectionTextureEnabled = value;
  42971. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42977. get: function () {
  42978. return StandardMaterial._EmissiveTextureEnabled;
  42979. },
  42980. set: function (value) {
  42981. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42982. return;
  42983. }
  42984. StandardMaterial._EmissiveTextureEnabled = value;
  42985. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42991. get: function () {
  42992. return StandardMaterial._SpecularTextureEnabled;
  42993. },
  42994. set: function (value) {
  42995. if (StandardMaterial._SpecularTextureEnabled === value) {
  42996. return;
  42997. }
  42998. StandardMaterial._SpecularTextureEnabled = value;
  42999. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43005. get: function () {
  43006. return StandardMaterial._BumpTextureEnabled;
  43007. },
  43008. set: function (value) {
  43009. if (StandardMaterial._BumpTextureEnabled === value) {
  43010. return;
  43011. }
  43012. StandardMaterial._BumpTextureEnabled = value;
  43013. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43014. },
  43015. enumerable: true,
  43016. configurable: true
  43017. });
  43018. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43019. get: function () {
  43020. return StandardMaterial._LightmapTextureEnabled;
  43021. },
  43022. set: function (value) {
  43023. if (StandardMaterial._LightmapTextureEnabled === value) {
  43024. return;
  43025. }
  43026. StandardMaterial._LightmapTextureEnabled = value;
  43027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43033. get: function () {
  43034. return StandardMaterial._RefractionTextureEnabled;
  43035. },
  43036. set: function (value) {
  43037. if (StandardMaterial._RefractionTextureEnabled === value) {
  43038. return;
  43039. }
  43040. StandardMaterial._RefractionTextureEnabled = value;
  43041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43042. },
  43043. enumerable: true,
  43044. configurable: true
  43045. });
  43046. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43047. get: function () {
  43048. return StandardMaterial._ColorGradingTextureEnabled;
  43049. },
  43050. set: function (value) {
  43051. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43052. return;
  43053. }
  43054. StandardMaterial._ColorGradingTextureEnabled = value;
  43055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43056. },
  43057. enumerable: true,
  43058. configurable: true
  43059. });
  43060. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43061. get: function () {
  43062. return StandardMaterial._FresnelEnabled;
  43063. },
  43064. set: function (value) {
  43065. if (StandardMaterial._FresnelEnabled === value) {
  43066. return;
  43067. }
  43068. StandardMaterial._FresnelEnabled = value;
  43069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43070. },
  43071. enumerable: true,
  43072. configurable: true
  43073. });
  43074. // Flags used to enable or disable a type of texture for all Standard Materials
  43075. StandardMaterial._DiffuseTextureEnabled = true;
  43076. StandardMaterial._AmbientTextureEnabled = true;
  43077. StandardMaterial._OpacityTextureEnabled = true;
  43078. StandardMaterial._ReflectionTextureEnabled = true;
  43079. StandardMaterial._EmissiveTextureEnabled = true;
  43080. StandardMaterial._SpecularTextureEnabled = true;
  43081. StandardMaterial._BumpTextureEnabled = true;
  43082. StandardMaterial._LightmapTextureEnabled = true;
  43083. StandardMaterial._RefractionTextureEnabled = true;
  43084. StandardMaterial._ColorGradingTextureEnabled = true;
  43085. StandardMaterial._FresnelEnabled = true;
  43086. __decorate([
  43087. BABYLON.serializeAsTexture("diffuseTexture")
  43088. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43089. __decorate([
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43091. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43092. __decorate([
  43093. BABYLON.serializeAsTexture("ambientTexture")
  43094. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43095. __decorate([
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsTexture("opacityTexture")
  43100. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43101. __decorate([
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43103. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43104. __decorate([
  43105. BABYLON.serializeAsTexture("reflectionTexture")
  43106. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43107. __decorate([
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43110. __decorate([
  43111. BABYLON.serializeAsTexture("emissiveTexture")
  43112. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43116. __decorate([
  43117. BABYLON.serializeAsTexture("specularTexture")
  43118. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43119. __decorate([
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], StandardMaterial.prototype, "specularTexture", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsTexture("bumpTexture")
  43124. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43125. __decorate([
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43128. __decorate([
  43129. BABYLON.serializeAsTexture("lightmapTexture")
  43130. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43134. __decorate([
  43135. BABYLON.serializeAsTexture("refractionTexture")
  43136. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43140. __decorate([
  43141. BABYLON.serializeAsColor3("ambient")
  43142. ], StandardMaterial.prototype, "ambientColor", void 0);
  43143. __decorate([
  43144. BABYLON.serializeAsColor3("diffuse")
  43145. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43146. __decorate([
  43147. BABYLON.serializeAsColor3("specular")
  43148. ], StandardMaterial.prototype, "specularColor", void 0);
  43149. __decorate([
  43150. BABYLON.serializeAsColor3("emissive")
  43151. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43152. __decorate([
  43153. BABYLON.serialize()
  43154. ], StandardMaterial.prototype, "specularPower", void 0);
  43155. __decorate([
  43156. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43157. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43158. __decorate([
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43161. __decorate([
  43162. BABYLON.serialize("useEmissiveAsIllumination")
  43163. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43164. __decorate([
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43167. __decorate([
  43168. BABYLON.serialize("linkEmissiveWithDiffuse")
  43169. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43170. __decorate([
  43171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43172. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43173. __decorate([
  43174. BABYLON.serialize("useSpecularOverAlpha")
  43175. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43176. __decorate([
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43178. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43179. __decorate([
  43180. BABYLON.serialize("useReflectionOverAlpha")
  43181. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43182. __decorate([
  43183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43184. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43185. __decorate([
  43186. BABYLON.serialize("disableLighting")
  43187. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43188. __decorate([
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43190. ], StandardMaterial.prototype, "disableLighting", void 0);
  43191. __decorate([
  43192. BABYLON.serialize("useObjectSpaceNormalMap")
  43193. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43194. __decorate([
  43195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43196. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43197. __decorate([
  43198. BABYLON.serialize("useParallax")
  43199. ], StandardMaterial.prototype, "_useParallax", void 0);
  43200. __decorate([
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43202. ], StandardMaterial.prototype, "useParallax", void 0);
  43203. __decorate([
  43204. BABYLON.serialize("useParallaxOcclusion")
  43205. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43206. __decorate([
  43207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43208. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43209. __decorate([
  43210. BABYLON.serialize()
  43211. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43212. __decorate([
  43213. BABYLON.serialize("roughness")
  43214. ], StandardMaterial.prototype, "_roughness", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], StandardMaterial.prototype, "roughness", void 0);
  43218. __decorate([
  43219. BABYLON.serialize()
  43220. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43221. __decorate([
  43222. BABYLON.serialize()
  43223. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43224. __decorate([
  43225. BABYLON.serialize()
  43226. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43227. __decorate([
  43228. BABYLON.serialize("useLightmapAsShadowmap")
  43229. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43230. __decorate([
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43232. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43233. __decorate([
  43234. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43235. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43236. __decorate([
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43238. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43239. __decorate([
  43240. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43241. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43242. __decorate([
  43243. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43244. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43245. __decorate([
  43246. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43247. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43248. __decorate([
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43250. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43251. __decorate([
  43252. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43253. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43254. __decorate([
  43255. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43256. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43257. __decorate([
  43258. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43259. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43260. __decorate([
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43262. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43263. __decorate([
  43264. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43265. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43266. __decorate([
  43267. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43268. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43269. __decorate([
  43270. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43271. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43272. __decorate([
  43273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43274. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43275. __decorate([
  43276. BABYLON.serialize("maxSimultaneousLights")
  43277. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43278. __decorate([
  43279. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43280. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43281. __decorate([
  43282. BABYLON.serialize("invertNormalMapX")
  43283. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43284. __decorate([
  43285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43286. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43287. __decorate([
  43288. BABYLON.serialize("invertNormalMapY")
  43289. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43290. __decorate([
  43291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43292. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43293. __decorate([
  43294. BABYLON.serialize("twoSidedLighting")
  43295. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43296. __decorate([
  43297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43298. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43299. __decorate([
  43300. BABYLON.serialize()
  43301. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43302. return StandardMaterial;
  43303. }(BABYLON.PushMaterial));
  43304. BABYLON.StandardMaterial = StandardMaterial;
  43305. })(BABYLON || (BABYLON = {}));
  43306. //# sourceMappingURL=babylon.standardMaterial.js.map
  43307. var BABYLON;
  43308. (function (BABYLON) {
  43309. /**
  43310. * Manages the defines for the PBR Material.
  43311. * @hiddenChildren
  43312. */
  43313. var PBRMaterialDefines = /** @class */ (function (_super) {
  43314. __extends(PBRMaterialDefines, _super);
  43315. /**
  43316. * Initializes the PBR Material defines.
  43317. */
  43318. function PBRMaterialDefines() {
  43319. var _this = _super.call(this) || this;
  43320. _this.PBR = true;
  43321. _this.MAINUV1 = false;
  43322. _this.MAINUV2 = false;
  43323. _this.UV1 = false;
  43324. _this.UV2 = false;
  43325. _this.ALBEDO = false;
  43326. _this.ALBEDODIRECTUV = 0;
  43327. _this.VERTEXCOLOR = false;
  43328. _this.AMBIENT = false;
  43329. _this.AMBIENTDIRECTUV = 0;
  43330. _this.AMBIENTINGRAYSCALE = false;
  43331. _this.OPACITY = false;
  43332. _this.VERTEXALPHA = false;
  43333. _this.OPACITYDIRECTUV = 0;
  43334. _this.OPACITYRGB = false;
  43335. _this.ALPHATEST = false;
  43336. _this.DEPTHPREPASS = false;
  43337. _this.ALPHABLEND = false;
  43338. _this.ALPHAFROMALBEDO = false;
  43339. _this.ALPHATESTVALUE = "0.5";
  43340. _this.SPECULAROVERALPHA = false;
  43341. _this.RADIANCEOVERALPHA = false;
  43342. _this.ALPHAFRESNEL = false;
  43343. _this.LINEARALPHAFRESNEL = false;
  43344. _this.PREMULTIPLYALPHA = false;
  43345. _this.EMISSIVE = false;
  43346. _this.EMISSIVEDIRECTUV = 0;
  43347. _this.REFLECTIVITY = false;
  43348. _this.REFLECTIVITYDIRECTUV = 0;
  43349. _this.SPECULARTERM = false;
  43350. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43351. _this.MICROSURFACEAUTOMATIC = false;
  43352. _this.LODBASEDMICROSFURACE = false;
  43353. _this.MICROSURFACEMAP = false;
  43354. _this.MICROSURFACEMAPDIRECTUV = 0;
  43355. _this.METALLICWORKFLOW = false;
  43356. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43357. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43358. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43359. _this.AOSTOREINMETALMAPRED = false;
  43360. _this.ENVIRONMENTBRDF = false;
  43361. _this.NORMAL = false;
  43362. _this.TANGENT = false;
  43363. _this.BUMP = false;
  43364. _this.BUMPDIRECTUV = 0;
  43365. _this.OBJECTSPACE_NORMALMAP = false;
  43366. _this.PARALLAX = false;
  43367. _this.PARALLAXOCCLUSION = false;
  43368. _this.NORMALXYSCALE = true;
  43369. _this.LIGHTMAP = false;
  43370. _this.LIGHTMAPDIRECTUV = 0;
  43371. _this.USELIGHTMAPASSHADOWMAP = false;
  43372. _this.GAMMALIGHTMAP = false;
  43373. _this.REFLECTION = false;
  43374. _this.REFLECTIONMAP_3D = false;
  43375. _this.REFLECTIONMAP_SPHERICAL = false;
  43376. _this.REFLECTIONMAP_PLANAR = false;
  43377. _this.REFLECTIONMAP_CUBIC = false;
  43378. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43379. _this.REFLECTIONMAP_PROJECTION = false;
  43380. _this.REFLECTIONMAP_SKYBOX = false;
  43381. _this.REFLECTIONMAP_EXPLICIT = false;
  43382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43385. _this.INVERTCUBICMAP = false;
  43386. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43387. _this.USESPHERICALINVERTEX = false;
  43388. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43389. _this.LODINREFLECTIONALPHA = false;
  43390. _this.GAMMAREFLECTION = false;
  43391. _this.RGBDREFLECTION = false;
  43392. _this.RADIANCEOCCLUSION = false;
  43393. _this.HORIZONOCCLUSION = false;
  43394. _this.REFRACTION = false;
  43395. _this.REFRACTIONMAP_3D = false;
  43396. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43397. _this.LODINREFRACTIONALPHA = false;
  43398. _this.GAMMAREFRACTION = false;
  43399. _this.RGBDREFRACTION = false;
  43400. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43401. _this.INSTANCES = false;
  43402. _this.NUM_BONE_INFLUENCERS = 0;
  43403. _this.BonesPerMesh = 0;
  43404. _this.NONUNIFORMSCALING = false;
  43405. _this.MORPHTARGETS = false;
  43406. _this.MORPHTARGETS_NORMAL = false;
  43407. _this.MORPHTARGETS_TANGENT = false;
  43408. _this.NUM_MORPH_INFLUENCERS = 0;
  43409. _this.IMAGEPROCESSING = false;
  43410. _this.VIGNETTE = false;
  43411. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43412. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43413. _this.TONEMAPPING = false;
  43414. _this.CONTRAST = false;
  43415. _this.COLORCURVES = false;
  43416. _this.COLORGRADING = false;
  43417. _this.COLORGRADING3D = false;
  43418. _this.SAMPLER3DGREENDEPTH = false;
  43419. _this.SAMPLER3DBGRMAP = false;
  43420. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43421. _this.EXPOSURE = false;
  43422. _this.USEPHYSICALLIGHTFALLOFF = false;
  43423. _this.TWOSIDEDLIGHTING = false;
  43424. _this.SHADOWFLOAT = false;
  43425. _this.CLIPPLANE = false;
  43426. _this.POINTSIZE = false;
  43427. _this.FOG = false;
  43428. _this.LOGARITHMICDEPTH = false;
  43429. _this.FORCENORMALFORWARD = false;
  43430. _this.SPECULARAA = false;
  43431. _this.UNLIT = false;
  43432. _this.rebuild();
  43433. return _this;
  43434. }
  43435. /**
  43436. * Resets the PBR Material defines.
  43437. */
  43438. PBRMaterialDefines.prototype.reset = function () {
  43439. _super.prototype.reset.call(this);
  43440. this.ALPHATESTVALUE = "0.5";
  43441. this.PBR = true;
  43442. };
  43443. return PBRMaterialDefines;
  43444. }(BABYLON.MaterialDefines));
  43445. /**
  43446. * The Physically based material base class of BJS.
  43447. *
  43448. * This offers the main features of a standard PBR material.
  43449. * For more information, please refer to the documentation :
  43450. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43451. */
  43452. var PBRBaseMaterial = /** @class */ (function (_super) {
  43453. __extends(PBRBaseMaterial, _super);
  43454. /**
  43455. * Instantiates a new PBRMaterial instance.
  43456. *
  43457. * @param name The material name
  43458. * @param scene The scene the material will be use in.
  43459. */
  43460. function PBRBaseMaterial(name, scene) {
  43461. var _this = _super.call(this, name, scene) || this;
  43462. /**
  43463. * Intensity of the direct lights e.g. the four lights available in your scene.
  43464. * This impacts both the direct diffuse and specular highlights.
  43465. */
  43466. _this._directIntensity = 1.0;
  43467. /**
  43468. * Intensity of the emissive part of the material.
  43469. * This helps controlling the emissive effect without modifying the emissive color.
  43470. */
  43471. _this._emissiveIntensity = 1.0;
  43472. /**
  43473. * Intensity of the environment e.g. how much the environment will light the object
  43474. * either through harmonics for rough material or through the refelction for shiny ones.
  43475. */
  43476. _this._environmentIntensity = 1.0;
  43477. /**
  43478. * This is a special control allowing the reduction of the specular highlights coming from the
  43479. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43480. */
  43481. _this._specularIntensity = 1.0;
  43482. /**
  43483. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43484. */
  43485. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43486. /**
  43487. * Debug Control allowing disabling the bump map on this material.
  43488. */
  43489. _this._disableBumpMap = false;
  43490. /**
  43491. * AKA Occlusion Texture Intensity in other nomenclature.
  43492. */
  43493. _this._ambientTextureStrength = 1.0;
  43494. /**
  43495. * The color of a material in ambient lighting.
  43496. */
  43497. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43498. /**
  43499. * AKA Diffuse Color in other nomenclature.
  43500. */
  43501. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43502. /**
  43503. * AKA Specular Color in other nomenclature.
  43504. */
  43505. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43506. /**
  43507. * The color applied when light is reflected from a material.
  43508. */
  43509. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43510. /**
  43511. * The color applied when light is emitted from a material.
  43512. */
  43513. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43514. /**
  43515. * AKA Glossiness in other nomenclature.
  43516. */
  43517. _this._microSurface = 0.9;
  43518. /**
  43519. * source material index of refraction (IOR)' / 'destination material IOR.
  43520. */
  43521. _this._indexOfRefraction = 0.66;
  43522. /**
  43523. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43524. */
  43525. _this._invertRefractionY = false;
  43526. /**
  43527. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43528. * Materials half opaque for instance using refraction could benefit from this control.
  43529. */
  43530. _this._linkRefractionWithTransparency = false;
  43531. /**
  43532. * Specifies that the material will use the light map as a show map.
  43533. */
  43534. _this._useLightmapAsShadowmap = false;
  43535. /**
  43536. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43537. * makes the reflect vector face the model (under horizon).
  43538. */
  43539. _this._useHorizonOcclusion = true;
  43540. /**
  43541. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43542. * too much the area relying on ambient texture to define their ambient occlusion.
  43543. */
  43544. _this._useRadianceOcclusion = true;
  43545. /**
  43546. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43547. */
  43548. _this._useAlphaFromAlbedoTexture = false;
  43549. /**
  43550. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43551. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43552. */
  43553. _this._useSpecularOverAlpha = true;
  43554. /**
  43555. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43556. */
  43557. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43558. /**
  43559. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43560. */
  43561. _this._useRoughnessFromMetallicTextureAlpha = true;
  43562. /**
  43563. * Specifies if the metallic texture contains the roughness information in its green channel.
  43564. */
  43565. _this._useRoughnessFromMetallicTextureGreen = false;
  43566. /**
  43567. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43568. */
  43569. _this._useMetallnessFromMetallicTextureBlue = false;
  43570. /**
  43571. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43572. */
  43573. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43574. /**
  43575. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43576. */
  43577. _this._useAmbientInGrayScale = false;
  43578. /**
  43579. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43580. * The material will try to infer what glossiness each pixel should be.
  43581. */
  43582. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43583. /**
  43584. * BJS is using an harcoded light falloff based on a manually sets up range.
  43585. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43586. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43587. */
  43588. _this._usePhysicalLightFalloff = true;
  43589. /**
  43590. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43591. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43592. */
  43593. _this._useRadianceOverAlpha = true;
  43594. /**
  43595. * Allows using an object space normal map (instead of tangent space).
  43596. */
  43597. _this._useObjectSpaceNormalMap = false;
  43598. /**
  43599. * Allows using the bump map in parallax mode.
  43600. */
  43601. _this._useParallax = false;
  43602. /**
  43603. * Allows using the bump map in parallax occlusion mode.
  43604. */
  43605. _this._useParallaxOcclusion = false;
  43606. /**
  43607. * Controls the scale bias of the parallax mode.
  43608. */
  43609. _this._parallaxScaleBias = 0.05;
  43610. /**
  43611. * If sets to true, disables all the lights affecting the material.
  43612. */
  43613. _this._disableLighting = false;
  43614. /**
  43615. * Number of Simultaneous lights allowed on the material.
  43616. */
  43617. _this._maxSimultaneousLights = 4;
  43618. /**
  43619. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43620. */
  43621. _this._invertNormalMapX = false;
  43622. /**
  43623. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43624. */
  43625. _this._invertNormalMapY = false;
  43626. /**
  43627. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43628. */
  43629. _this._twoSidedLighting = false;
  43630. /**
  43631. * Defines the alpha limits in alpha test mode.
  43632. */
  43633. _this._alphaCutOff = 0.4;
  43634. /**
  43635. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43636. */
  43637. _this._forceAlphaTest = false;
  43638. /**
  43639. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43640. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43641. */
  43642. _this._useAlphaFresnel = false;
  43643. /**
  43644. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43645. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43646. */
  43647. _this._useLinearAlphaFresnel = false;
  43648. /**
  43649. * The transparency mode of the material.
  43650. */
  43651. _this._transparencyMode = null;
  43652. /**
  43653. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43654. * from cos thetav and roughness:
  43655. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43656. */
  43657. _this._environmentBRDFTexture = null;
  43658. /**
  43659. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43660. */
  43661. _this._forceIrradianceInFragment = false;
  43662. /**
  43663. * Force normal to face away from face.
  43664. */
  43665. _this._forceNormalForward = false;
  43666. /**
  43667. * Enables specular anti aliasing in the PBR shader.
  43668. * It will both interacts on the Geometry for analytical and IBL lighting.
  43669. * It also prefilter the roughness map based on the bump values.
  43670. */
  43671. _this._enableSpecularAntiAliasing = false;
  43672. /**
  43673. * Stores the available render targets.
  43674. */
  43675. _this._renderTargets = new BABYLON.SmartArray(16);
  43676. /**
  43677. * Sets the global ambient color for the material used in lighting calculations.
  43678. */
  43679. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43680. /**
  43681. * If set to true, no lighting calculations will be applied.
  43682. */
  43683. _this._unlit = false;
  43684. // Setup the default processing configuration to the scene.
  43685. _this._attachImageProcessingConfiguration(null);
  43686. _this.getRenderTargetTextures = function () {
  43687. _this._renderTargets.reset();
  43688. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43689. _this._renderTargets.push(_this._reflectionTexture);
  43690. }
  43691. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43692. _this._renderTargets.push(_this._refractionTexture);
  43693. }
  43694. return _this._renderTargets;
  43695. };
  43696. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43697. return _this;
  43698. }
  43699. /**
  43700. * Attaches a new image processing configuration to the PBR Material.
  43701. * @param configuration
  43702. */
  43703. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43704. var _this = this;
  43705. if (configuration === this._imageProcessingConfiguration) {
  43706. return;
  43707. }
  43708. // Detaches observer.
  43709. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43710. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43711. }
  43712. // Pick the scene configuration if needed.
  43713. if (!configuration) {
  43714. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43715. }
  43716. else {
  43717. this._imageProcessingConfiguration = configuration;
  43718. }
  43719. // Attaches observer.
  43720. if (this._imageProcessingConfiguration) {
  43721. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43722. _this._markAllSubMeshesAsImageProcessingDirty();
  43723. });
  43724. }
  43725. };
  43726. /**
  43727. * Gets the name of the material class.
  43728. */
  43729. PBRBaseMaterial.prototype.getClassName = function () {
  43730. return "PBRBaseMaterial";
  43731. };
  43732. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43733. /**
  43734. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43735. */
  43736. get: function () {
  43737. return this._useLogarithmicDepth;
  43738. },
  43739. /**
  43740. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43741. */
  43742. set: function (value) {
  43743. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43744. },
  43745. enumerable: true,
  43746. configurable: true
  43747. });
  43748. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43749. /**
  43750. * Gets the current transparency mode.
  43751. */
  43752. get: function () {
  43753. return this._transparencyMode;
  43754. },
  43755. /**
  43756. * Sets the transparency mode of the material.
  43757. *
  43758. * | Value | Type | Description |
  43759. * | ----- | ----------------------------------- | ----------- |
  43760. * | 0 | OPAQUE | |
  43761. * | 1 | ALPHATEST | |
  43762. * | 2 | ALPHABLEND | |
  43763. * | 3 | ALPHATESTANDBLEND | |
  43764. *
  43765. */
  43766. set: function (value) {
  43767. if (this._transparencyMode === value) {
  43768. return;
  43769. }
  43770. this._transparencyMode = value;
  43771. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43772. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43773. },
  43774. enumerable: true,
  43775. configurable: true
  43776. });
  43777. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43778. /**
  43779. * Returns true if alpha blending should be disabled.
  43780. */
  43781. get: function () {
  43782. return (this._linkRefractionWithTransparency ||
  43783. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43784. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43785. },
  43786. enumerable: true,
  43787. configurable: true
  43788. });
  43789. /**
  43790. * Specifies whether or not this material should be rendered in alpha blend mode.
  43791. */
  43792. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43793. if (this._disableAlphaBlending) {
  43794. return false;
  43795. }
  43796. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43797. };
  43798. /**
  43799. * Specifies if the mesh will require alpha blending.
  43800. * @param mesh - BJS mesh.
  43801. */
  43802. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43803. if (this._disableAlphaBlending) {
  43804. return false;
  43805. }
  43806. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43807. };
  43808. /**
  43809. * Specifies whether or not this material should be rendered in alpha test mode.
  43810. */
  43811. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43812. if (this._forceAlphaTest) {
  43813. return true;
  43814. }
  43815. if (this._linkRefractionWithTransparency) {
  43816. return false;
  43817. }
  43818. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43819. };
  43820. /**
  43821. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43822. */
  43823. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43824. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43825. };
  43826. /**
  43827. * Gets the texture used for the alpha test.
  43828. */
  43829. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43830. return this._albedoTexture;
  43831. };
  43832. /**
  43833. * Specifies that the submesh is ready to be used.
  43834. * @param mesh - BJS mesh.
  43835. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43836. * @param useInstances - Specifies that instances should be used.
  43837. * @returns - boolean indicating that the submesh is ready or not.
  43838. */
  43839. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43840. if (subMesh.effect && this.isFrozen) {
  43841. if (this._wasPreviouslyReady) {
  43842. return true;
  43843. }
  43844. }
  43845. if (!subMesh._materialDefines) {
  43846. subMesh._materialDefines = new PBRMaterialDefines();
  43847. }
  43848. var defines = subMesh._materialDefines;
  43849. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43850. if (defines._renderId === this.getScene().getRenderId()) {
  43851. return true;
  43852. }
  43853. }
  43854. var scene = this.getScene();
  43855. var engine = scene.getEngine();
  43856. if (defines._areTexturesDirty) {
  43857. if (scene.texturesEnabled) {
  43858. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43859. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43860. return false;
  43861. }
  43862. }
  43863. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43864. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43865. return false;
  43866. }
  43867. }
  43868. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43869. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43870. return false;
  43871. }
  43872. }
  43873. var reflectionTexture = this._getReflectionTexture();
  43874. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43875. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43876. return false;
  43877. }
  43878. }
  43879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43880. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43881. return false;
  43882. }
  43883. }
  43884. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43885. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43886. return false;
  43887. }
  43888. }
  43889. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43890. if (this._metallicTexture) {
  43891. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. }
  43895. else if (this._reflectivityTexture) {
  43896. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43897. return false;
  43898. }
  43899. }
  43900. if (this._microSurfaceTexture) {
  43901. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43902. return false;
  43903. }
  43904. }
  43905. }
  43906. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43907. // Bump texture cannot be not blocking.
  43908. if (!this._bumpTexture.isReady()) {
  43909. return false;
  43910. }
  43911. }
  43912. var refractionTexture = this._getRefractionTexture();
  43913. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43914. if (!refractionTexture.isReadyOrNotBlocking()) {
  43915. return false;
  43916. }
  43917. }
  43918. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43919. // This is blocking.
  43920. if (!this._environmentBRDFTexture.isReady()) {
  43921. return false;
  43922. }
  43923. }
  43924. }
  43925. }
  43926. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43927. if (!this._imageProcessingConfiguration.isReady()) {
  43928. return false;
  43929. }
  43930. }
  43931. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43932. mesh.createNormals(true);
  43933. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43934. }
  43935. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43936. if (effect) {
  43937. scene.resetCachedMaterial();
  43938. subMesh.setEffect(effect, defines);
  43939. this.buildUniformLayout();
  43940. }
  43941. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43942. return false;
  43943. }
  43944. defines._renderId = scene.getRenderId();
  43945. this._wasPreviouslyReady = true;
  43946. return true;
  43947. };
  43948. /**
  43949. * Specifies if the material uses metallic roughness workflow.
  43950. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43951. */
  43952. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43953. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43954. return true;
  43955. }
  43956. return false;
  43957. };
  43958. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43959. if (onCompiled === void 0) { onCompiled = null; }
  43960. if (onError === void 0) { onError = null; }
  43961. if (useInstances === void 0) { useInstances = null; }
  43962. if (useClipPlane === void 0) { useClipPlane = null; }
  43963. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43964. if (!defines.isDirty) {
  43965. return null;
  43966. }
  43967. defines.markAsProcessed();
  43968. var scene = this.getScene();
  43969. var engine = scene.getEngine();
  43970. // Fallbacks
  43971. var fallbacks = new BABYLON.EffectFallbacks();
  43972. var fallbackRank = 0;
  43973. if (defines.USESPHERICALINVERTEX) {
  43974. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43975. }
  43976. if (defines.FOG) {
  43977. fallbacks.addFallback(fallbackRank, "FOG");
  43978. }
  43979. if (defines.SPECULARAA) {
  43980. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43981. }
  43982. if (defines.POINTSIZE) {
  43983. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43984. }
  43985. if (defines.LOGARITHMICDEPTH) {
  43986. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43987. }
  43988. if (defines.PARALLAX) {
  43989. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43990. }
  43991. if (defines.PARALLAXOCCLUSION) {
  43992. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43993. }
  43994. if (defines.ENVIRONMENTBRDF) {
  43995. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43996. }
  43997. if (defines.TANGENT) {
  43998. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43999. }
  44000. if (defines.BUMP) {
  44001. fallbacks.addFallback(fallbackRank++, "BUMP");
  44002. }
  44003. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44004. if (defines.SPECULARTERM) {
  44005. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44006. }
  44007. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44008. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44009. }
  44010. if (defines.LIGHTMAP) {
  44011. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44012. }
  44013. if (defines.NORMAL) {
  44014. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44015. }
  44016. if (defines.AMBIENT) {
  44017. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44018. }
  44019. if (defines.EMISSIVE) {
  44020. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44021. }
  44022. if (defines.VERTEXCOLOR) {
  44023. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44024. }
  44025. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44026. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44027. }
  44028. if (defines.MORPHTARGETS) {
  44029. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44030. }
  44031. //Attributes
  44032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44033. if (defines.NORMAL) {
  44034. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44035. }
  44036. if (defines.TANGENT) {
  44037. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44038. }
  44039. if (defines.UV1) {
  44040. attribs.push(BABYLON.VertexBuffer.UVKind);
  44041. }
  44042. if (defines.UV2) {
  44043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44044. }
  44045. if (defines.VERTEXCOLOR) {
  44046. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44047. }
  44048. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44049. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44050. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44051. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44052. "vFogInfos", "vFogColor", "pointSize",
  44053. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44054. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44055. "mBones",
  44056. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44057. "vLightingIntensity",
  44058. "logarithmicDepthConstant",
  44059. "vSphericalX", "vSphericalY", "vSphericalZ",
  44060. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44061. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44062. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44063. "vTangentSpaceParams"
  44064. ];
  44065. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44066. "bumpSampler", "lightmapSampler", "opacitySampler",
  44067. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44068. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44069. "microSurfaceSampler", "environmentBrdfSampler"];
  44070. var uniformBuffers = ["Material", "Scene"];
  44071. if (BABYLON.ImageProcessingConfiguration) {
  44072. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44073. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44074. }
  44075. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44076. uniformsNames: uniforms,
  44077. uniformBuffersNames: uniformBuffers,
  44078. samplers: samplers,
  44079. defines: defines,
  44080. maxSimultaneousLights: this._maxSimultaneousLights
  44081. });
  44082. var join = defines.toString();
  44083. return engine.createEffect("pbr", {
  44084. attributes: attribs,
  44085. uniformsNames: uniforms,
  44086. uniformBuffersNames: uniformBuffers,
  44087. samplers: samplers,
  44088. defines: join,
  44089. fallbacks: fallbacks,
  44090. onCompiled: onCompiled,
  44091. onError: onError,
  44092. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44093. }, engine);
  44094. };
  44095. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44096. if (useInstances === void 0) { useInstances = null; }
  44097. if (useClipPlane === void 0) { useClipPlane = null; }
  44098. var scene = this.getScene();
  44099. var engine = scene.getEngine();
  44100. // Lights
  44101. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44102. defines._needNormals = true;
  44103. // Textures
  44104. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44105. if (defines._areTexturesDirty) {
  44106. defines._needUVs = false;
  44107. if (scene.texturesEnabled) {
  44108. if (scene.getEngine().getCaps().textureLOD) {
  44109. defines.LODBASEDMICROSFURACE = true;
  44110. }
  44111. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44113. }
  44114. else {
  44115. defines.ALBEDO = false;
  44116. }
  44117. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44118. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44119. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44120. }
  44121. else {
  44122. defines.AMBIENT = false;
  44123. }
  44124. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44125. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44126. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44127. }
  44128. else {
  44129. defines.OPACITY = false;
  44130. }
  44131. var reflectionTexture = this._getReflectionTexture();
  44132. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44133. defines.REFLECTION = true;
  44134. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44135. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44136. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44137. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44138. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44139. defines.INVERTCUBICMAP = true;
  44140. }
  44141. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44142. switch (reflectionTexture.coordinatesMode) {
  44143. case BABYLON.Texture.EXPLICIT_MODE:
  44144. defines.REFLECTIONMAP_EXPLICIT = true;
  44145. break;
  44146. case BABYLON.Texture.PLANAR_MODE:
  44147. defines.REFLECTIONMAP_PLANAR = true;
  44148. break;
  44149. case BABYLON.Texture.PROJECTION_MODE:
  44150. defines.REFLECTIONMAP_PROJECTION = true;
  44151. break;
  44152. case BABYLON.Texture.SKYBOX_MODE:
  44153. defines.REFLECTIONMAP_SKYBOX = true;
  44154. break;
  44155. case BABYLON.Texture.SPHERICAL_MODE:
  44156. defines.REFLECTIONMAP_SPHERICAL = true;
  44157. break;
  44158. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44159. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44160. break;
  44161. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44162. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44163. break;
  44164. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44165. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44166. break;
  44167. case BABYLON.Texture.CUBIC_MODE:
  44168. case BABYLON.Texture.INVCUBIC_MODE:
  44169. default:
  44170. defines.REFLECTIONMAP_CUBIC = true;
  44171. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44172. break;
  44173. }
  44174. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44175. if (reflectionTexture.sphericalPolynomial) {
  44176. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44177. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44178. defines.USESPHERICALINVERTEX = false;
  44179. }
  44180. else {
  44181. defines.USESPHERICALINVERTEX = true;
  44182. }
  44183. }
  44184. }
  44185. }
  44186. else {
  44187. defines.REFLECTION = false;
  44188. defines.REFLECTIONMAP_3D = false;
  44189. defines.REFLECTIONMAP_SPHERICAL = false;
  44190. defines.REFLECTIONMAP_PLANAR = false;
  44191. defines.REFLECTIONMAP_CUBIC = false;
  44192. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44193. defines.REFLECTIONMAP_PROJECTION = false;
  44194. defines.REFLECTIONMAP_SKYBOX = false;
  44195. defines.REFLECTIONMAP_EXPLICIT = false;
  44196. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44197. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44198. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44199. defines.INVERTCUBICMAP = false;
  44200. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44201. defines.USESPHERICALINVERTEX = false;
  44202. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44203. defines.LODINREFLECTIONALPHA = false;
  44204. defines.GAMMAREFLECTION = false;
  44205. defines.RGBDREFLECTION = false;
  44206. }
  44207. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44208. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44209. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44210. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44211. }
  44212. else {
  44213. defines.LIGHTMAP = false;
  44214. }
  44215. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44216. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44217. }
  44218. else {
  44219. defines.EMISSIVE = false;
  44220. }
  44221. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44222. if (this._metallicTexture) {
  44223. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44224. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44225. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44226. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44227. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44228. }
  44229. else if (this._reflectivityTexture) {
  44230. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44231. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44232. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44233. }
  44234. else {
  44235. defines.REFLECTIVITY = false;
  44236. }
  44237. if (this._microSurfaceTexture) {
  44238. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44239. }
  44240. else {
  44241. defines.MICROSURFACEMAP = false;
  44242. }
  44243. }
  44244. else {
  44245. defines.REFLECTIVITY = false;
  44246. defines.MICROSURFACEMAP = false;
  44247. }
  44248. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44250. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44251. defines.PARALLAX = true;
  44252. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44253. }
  44254. else {
  44255. defines.PARALLAX = false;
  44256. }
  44257. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44258. }
  44259. else {
  44260. defines.BUMP = false;
  44261. }
  44262. var refractionTexture = this._getRefractionTexture();
  44263. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44264. defines.REFRACTION = true;
  44265. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44266. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44267. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44268. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44269. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44270. if (this._linkRefractionWithTransparency) {
  44271. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44272. }
  44273. }
  44274. else {
  44275. defines.REFRACTION = false;
  44276. }
  44277. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44278. defines.ENVIRONMENTBRDF = true;
  44279. }
  44280. else {
  44281. defines.ENVIRONMENTBRDF = false;
  44282. }
  44283. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44284. defines.ALPHAFROMALBEDO = true;
  44285. }
  44286. else {
  44287. defines.ALPHAFROMALBEDO = false;
  44288. }
  44289. }
  44290. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44291. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44292. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44293. if (!this.backFaceCulling && this._twoSidedLighting) {
  44294. defines.TWOSIDEDLIGHTING = true;
  44295. }
  44296. else {
  44297. defines.TWOSIDEDLIGHTING = false;
  44298. }
  44299. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44300. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44301. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44302. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44303. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44304. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44305. }
  44306. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44307. this._imageProcessingConfiguration.prepareDefines(defines);
  44308. }
  44309. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44310. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44311. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44312. // Misc.
  44313. if (defines._areMiscDirty) {
  44314. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44315. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44316. }
  44317. // Values that need to be evaluated on every frame
  44318. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44319. // Attribs
  44320. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44321. };
  44322. /**
  44323. * Force shader compilation
  44324. */
  44325. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44326. var _this = this;
  44327. var localOptions = __assign({ clipPlane: false }, options);
  44328. var defines = new PBRMaterialDefines();
  44329. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44330. if (effect.isReady()) {
  44331. if (onCompiled) {
  44332. onCompiled(this);
  44333. }
  44334. }
  44335. else {
  44336. effect.onCompileObservable.add(function () {
  44337. if (onCompiled) {
  44338. onCompiled(_this);
  44339. }
  44340. });
  44341. }
  44342. };
  44343. /**
  44344. * Initializes the uniform buffer layout for the shader.
  44345. */
  44346. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44347. // Order is important !
  44348. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44349. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44350. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44351. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44352. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44353. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44354. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44355. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44356. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44357. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44358. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44359. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44360. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44361. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44362. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44363. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44364. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44365. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44366. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44367. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44368. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44369. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44370. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44371. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44372. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44373. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44374. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44375. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44376. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44377. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44378. this._uniformBuffer.addUniform("pointSize", 1);
  44379. this._uniformBuffer.create();
  44380. };
  44381. /**
  44382. * Unbinds the textures.
  44383. */
  44384. PBRBaseMaterial.prototype.unbind = function () {
  44385. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44386. this._uniformBuffer.setTexture("reflectionSampler", null);
  44387. }
  44388. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44389. this._uniformBuffer.setTexture("refractionSampler", null);
  44390. }
  44391. _super.prototype.unbind.call(this);
  44392. };
  44393. /**
  44394. * Binds the submesh data.
  44395. * @param world - The world matrix.
  44396. * @param mesh - The BJS mesh.
  44397. * @param subMesh - A submesh of the BJS mesh.
  44398. */
  44399. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44400. var scene = this.getScene();
  44401. var defines = subMesh._materialDefines;
  44402. if (!defines) {
  44403. return;
  44404. }
  44405. var effect = subMesh.effect;
  44406. if (!effect) {
  44407. return;
  44408. }
  44409. this._activeEffect = effect;
  44410. // Matrices
  44411. this.bindOnlyWorldMatrix(world);
  44412. // Normal Matrix
  44413. if (defines.OBJECTSPACE_NORMALMAP) {
  44414. world.toNormalMatrix(this._normalMatrix);
  44415. this.bindOnlyNormalMatrix(this._normalMatrix);
  44416. }
  44417. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44418. // Bones
  44419. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44420. var reflectionTexture = null;
  44421. if (mustRebind) {
  44422. this._uniformBuffer.bindToEffect(effect, "Material");
  44423. this.bindViewProjection(effect);
  44424. reflectionTexture = this._getReflectionTexture();
  44425. var refractionTexture = this._getRefractionTexture();
  44426. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44427. // Texture uniforms
  44428. if (scene.texturesEnabled) {
  44429. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44430. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44431. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44432. }
  44433. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44434. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44435. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44436. }
  44437. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44438. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44439. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44440. }
  44441. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44442. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44443. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44444. if (reflectionTexture.boundingBoxSize) {
  44445. var cubeTexture = reflectionTexture;
  44446. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44447. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44448. }
  44449. var polynomials = reflectionTexture.sphericalPolynomial;
  44450. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44451. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44452. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44453. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44454. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44455. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44456. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44457. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44458. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44459. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44460. }
  44461. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44462. }
  44463. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44464. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44465. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44466. }
  44467. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44468. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44469. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44470. }
  44471. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44472. if (this._metallicTexture) {
  44473. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44474. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44475. }
  44476. else if (this._reflectivityTexture) {
  44477. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44478. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44479. }
  44480. if (this._microSurfaceTexture) {
  44481. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44482. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44483. }
  44484. }
  44485. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44486. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44487. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44488. if (scene._mirroredCameraPosition) {
  44489. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44490. }
  44491. else {
  44492. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44493. }
  44494. }
  44495. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44496. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44497. var depth = 1.0;
  44498. if (!refractionTexture.isCube) {
  44499. if (refractionTexture.depth) {
  44500. depth = refractionTexture.depth;
  44501. }
  44502. }
  44503. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44504. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44505. }
  44506. }
  44507. // Point size
  44508. if (this.pointsCloud) {
  44509. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44510. }
  44511. // Colors
  44512. if (defines.METALLICWORKFLOW) {
  44513. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44514. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44515. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44516. }
  44517. else {
  44518. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44519. }
  44520. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44521. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44522. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44523. // Misc
  44524. this._lightingInfos.x = this._directIntensity;
  44525. this._lightingInfos.y = this._emissiveIntensity;
  44526. this._lightingInfos.z = this._environmentIntensity;
  44527. this._lightingInfos.w = this._specularIntensity;
  44528. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44529. }
  44530. // Textures
  44531. if (scene.texturesEnabled) {
  44532. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44533. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44534. }
  44535. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44536. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44537. }
  44538. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44539. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44540. }
  44541. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44542. if (defines.LODBASEDMICROSFURACE) {
  44543. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44544. }
  44545. else {
  44546. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44547. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44548. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44549. }
  44550. }
  44551. if (defines.ENVIRONMENTBRDF) {
  44552. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44553. }
  44554. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44555. if (defines.LODBASEDMICROSFURACE) {
  44556. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44557. }
  44558. else {
  44559. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44560. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44561. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44562. }
  44563. }
  44564. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44565. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44566. }
  44567. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44568. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44569. }
  44570. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44571. if (this._metallicTexture) {
  44572. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44573. }
  44574. else if (this._reflectivityTexture) {
  44575. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44576. }
  44577. if (this._microSurfaceTexture) {
  44578. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44579. }
  44580. }
  44581. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44582. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44583. }
  44584. }
  44585. // Clip plane
  44586. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44587. // Colors
  44588. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44589. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44590. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44591. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44592. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44593. }
  44594. if (mustRebind || !this.isFrozen) {
  44595. // Lights
  44596. if (scene.lightsEnabled && !this._disableLighting) {
  44597. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44598. }
  44599. // View
  44600. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44601. this.bindView(effect);
  44602. }
  44603. // Fog
  44604. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44605. // Morph targets
  44606. if (defines.NUM_MORPH_INFLUENCERS) {
  44607. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44608. }
  44609. // image processing
  44610. this._imageProcessingConfiguration.bind(this._activeEffect);
  44611. // Log. depth
  44612. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44613. }
  44614. this._uniformBuffer.update();
  44615. this._afterBind(mesh, this._activeEffect);
  44616. };
  44617. /**
  44618. * Returns the animatable textures.
  44619. * @returns - Array of animatable textures.
  44620. */
  44621. PBRBaseMaterial.prototype.getAnimatables = function () {
  44622. var results = [];
  44623. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44624. results.push(this._albedoTexture);
  44625. }
  44626. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44627. results.push(this._ambientTexture);
  44628. }
  44629. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44630. results.push(this._opacityTexture);
  44631. }
  44632. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44633. results.push(this._reflectionTexture);
  44634. }
  44635. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44636. results.push(this._emissiveTexture);
  44637. }
  44638. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44639. results.push(this._metallicTexture);
  44640. }
  44641. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44642. results.push(this._reflectivityTexture);
  44643. }
  44644. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44645. results.push(this._bumpTexture);
  44646. }
  44647. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44648. results.push(this._lightmapTexture);
  44649. }
  44650. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44651. results.push(this._refractionTexture);
  44652. }
  44653. return results;
  44654. };
  44655. /**
  44656. * Returns the texture used for reflections.
  44657. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44658. */
  44659. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44660. if (this._reflectionTexture) {
  44661. return this._reflectionTexture;
  44662. }
  44663. return this.getScene().environmentTexture;
  44664. };
  44665. /**
  44666. * Returns the texture used for refraction or null if none is used.
  44667. * @returns - Refection texture if present. If no refraction texture and refraction
  44668. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44669. */
  44670. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44671. if (this._refractionTexture) {
  44672. return this._refractionTexture;
  44673. }
  44674. if (this._linkRefractionWithTransparency) {
  44675. return this.getScene().environmentTexture;
  44676. }
  44677. return null;
  44678. };
  44679. /**
  44680. * Disposes the resources of the material.
  44681. * @param forceDisposeEffect - Forces the disposal of effects.
  44682. * @param forceDisposeTextures - Forces the disposal of all textures.
  44683. */
  44684. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44685. if (forceDisposeTextures) {
  44686. if (this._albedoTexture) {
  44687. this._albedoTexture.dispose();
  44688. }
  44689. if (this._ambientTexture) {
  44690. this._ambientTexture.dispose();
  44691. }
  44692. if (this._opacityTexture) {
  44693. this._opacityTexture.dispose();
  44694. }
  44695. if (this._reflectionTexture) {
  44696. this._reflectionTexture.dispose();
  44697. }
  44698. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44699. this._environmentBRDFTexture.dispose();
  44700. }
  44701. if (this._emissiveTexture) {
  44702. this._emissiveTexture.dispose();
  44703. }
  44704. if (this._metallicTexture) {
  44705. this._metallicTexture.dispose();
  44706. }
  44707. if (this._reflectivityTexture) {
  44708. this._reflectivityTexture.dispose();
  44709. }
  44710. if (this._bumpTexture) {
  44711. this._bumpTexture.dispose();
  44712. }
  44713. if (this._lightmapTexture) {
  44714. this._lightmapTexture.dispose();
  44715. }
  44716. if (this._refractionTexture) {
  44717. this._refractionTexture.dispose();
  44718. }
  44719. }
  44720. this._renderTargets.dispose();
  44721. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44722. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44723. }
  44724. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44725. };
  44726. /**
  44727. * Stores the reflectivity values based on metallic roughness workflow.
  44728. */
  44729. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44730. __decorate([
  44731. BABYLON.serializeAsImageProcessingConfiguration()
  44732. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44733. __decorate([
  44734. BABYLON.serialize()
  44735. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44736. __decorate([
  44737. BABYLON.serialize()
  44738. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44739. return PBRBaseMaterial;
  44740. }(BABYLON.PushMaterial));
  44741. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44742. })(BABYLON || (BABYLON = {}));
  44743. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44744. var BABYLON;
  44745. (function (BABYLON) {
  44746. /**
  44747. * The Physically based simple base material of BJS.
  44748. *
  44749. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44750. * It is used as the base class for both the specGloss and metalRough conventions.
  44751. */
  44752. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44753. __extends(PBRBaseSimpleMaterial, _super);
  44754. /**
  44755. * Instantiates a new PBRMaterial instance.
  44756. *
  44757. * @param name The material name
  44758. * @param scene The scene the material will be use in.
  44759. */
  44760. function PBRBaseSimpleMaterial(name, scene) {
  44761. var _this = _super.call(this, name, scene) || this;
  44762. /**
  44763. * Number of Simultaneous lights allowed on the material.
  44764. */
  44765. _this.maxSimultaneousLights = 4;
  44766. /**
  44767. * If sets to true, disables all the lights affecting the material.
  44768. */
  44769. _this.disableLighting = false;
  44770. /**
  44771. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44772. */
  44773. _this.invertNormalMapX = false;
  44774. /**
  44775. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44776. */
  44777. _this.invertNormalMapY = false;
  44778. /**
  44779. * Emissivie color used to self-illuminate the model.
  44780. */
  44781. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44782. /**
  44783. * Occlusion Channel Strenght.
  44784. */
  44785. _this.occlusionStrength = 1.0;
  44786. _this.useLightmapAsShadowmap = false;
  44787. _this._useAlphaFromAlbedoTexture = true;
  44788. _this._useAmbientInGrayScale = true;
  44789. return _this;
  44790. }
  44791. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44792. /**
  44793. * Gets the current double sided mode.
  44794. */
  44795. get: function () {
  44796. return this._twoSidedLighting;
  44797. },
  44798. /**
  44799. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44800. */
  44801. set: function (value) {
  44802. if (this._twoSidedLighting === value) {
  44803. return;
  44804. }
  44805. this._twoSidedLighting = value;
  44806. this.backFaceCulling = !value;
  44807. this._markAllSubMeshesAsTexturesDirty();
  44808. },
  44809. enumerable: true,
  44810. configurable: true
  44811. });
  44812. /**
  44813. * Return the active textures of the material.
  44814. */
  44815. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44816. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44817. if (this.environmentTexture) {
  44818. activeTextures.push(this.environmentTexture);
  44819. }
  44820. if (this.normalTexture) {
  44821. activeTextures.push(this.normalTexture);
  44822. }
  44823. if (this.emissiveTexture) {
  44824. activeTextures.push(this.emissiveTexture);
  44825. }
  44826. if (this.occlusionTexture) {
  44827. activeTextures.push(this.occlusionTexture);
  44828. }
  44829. if (this.lightmapTexture) {
  44830. activeTextures.push(this.lightmapTexture);
  44831. }
  44832. return activeTextures;
  44833. };
  44834. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44835. if (_super.prototype.hasTexture.call(this, texture)) {
  44836. return true;
  44837. }
  44838. if (this.lightmapTexture === texture) {
  44839. return true;
  44840. }
  44841. return false;
  44842. };
  44843. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44844. return "PBRBaseSimpleMaterial";
  44845. };
  44846. __decorate([
  44847. BABYLON.serialize(),
  44848. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44849. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44850. __decorate([
  44851. BABYLON.serialize(),
  44852. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44853. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44854. __decorate([
  44855. BABYLON.serializeAsTexture(),
  44856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44857. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44858. __decorate([
  44859. BABYLON.serialize(),
  44860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44861. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44862. __decorate([
  44863. BABYLON.serialize(),
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44865. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44866. __decorate([
  44867. BABYLON.serializeAsTexture(),
  44868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44869. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44870. __decorate([
  44871. BABYLON.serializeAsColor3("emissive"),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44873. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44874. __decorate([
  44875. BABYLON.serializeAsTexture(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44877. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44878. __decorate([
  44879. BABYLON.serialize(),
  44880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44881. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44882. __decorate([
  44883. BABYLON.serializeAsTexture(),
  44884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44885. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44886. __decorate([
  44887. BABYLON.serialize(),
  44888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44889. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44890. __decorate([
  44891. BABYLON.serialize()
  44892. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44893. __decorate([
  44894. BABYLON.serializeAsTexture(),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44896. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44897. __decorate([
  44898. BABYLON.serialize(),
  44899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44900. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44901. return PBRBaseSimpleMaterial;
  44902. }(BABYLON.PBRBaseMaterial));
  44903. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44904. })(BABYLON || (BABYLON = {}));
  44905. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44906. var BABYLON;
  44907. (function (BABYLON) {
  44908. /**
  44909. * The Physically based material of BJS.
  44910. *
  44911. * This offers the main features of a standard PBR material.
  44912. * For more information, please refer to the documentation :
  44913. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44914. */
  44915. var PBRMaterial = /** @class */ (function (_super) {
  44916. __extends(PBRMaterial, _super);
  44917. /**
  44918. * Instantiates a new PBRMaterial instance.
  44919. *
  44920. * @param name The material name
  44921. * @param scene The scene the material will be use in.
  44922. */
  44923. function PBRMaterial(name, scene) {
  44924. var _this = _super.call(this, name, scene) || this;
  44925. /**
  44926. * Intensity of the direct lights e.g. the four lights available in your scene.
  44927. * This impacts both the direct diffuse and specular highlights.
  44928. */
  44929. _this.directIntensity = 1.0;
  44930. /**
  44931. * Intensity of the emissive part of the material.
  44932. * This helps controlling the emissive effect without modifying the emissive color.
  44933. */
  44934. _this.emissiveIntensity = 1.0;
  44935. /**
  44936. * Intensity of the environment e.g. how much the environment will light the object
  44937. * either through harmonics for rough material or through the refelction for shiny ones.
  44938. */
  44939. _this.environmentIntensity = 1.0;
  44940. /**
  44941. * This is a special control allowing the reduction of the specular highlights coming from the
  44942. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44943. */
  44944. _this.specularIntensity = 1.0;
  44945. /**
  44946. * Debug Control allowing disabling the bump map on this material.
  44947. */
  44948. _this.disableBumpMap = false;
  44949. /**
  44950. * AKA Occlusion Texture Intensity in other nomenclature.
  44951. */
  44952. _this.ambientTextureStrength = 1.0;
  44953. /**
  44954. * The color of a material in ambient lighting.
  44955. */
  44956. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44957. /**
  44958. * AKA Diffuse Color in other nomenclature.
  44959. */
  44960. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44961. /**
  44962. * AKA Specular Color in other nomenclature.
  44963. */
  44964. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44965. /**
  44966. * The color reflected from the material.
  44967. */
  44968. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44969. /**
  44970. * The color emitted from the material.
  44971. */
  44972. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44973. /**
  44974. * AKA Glossiness in other nomenclature.
  44975. */
  44976. _this.microSurface = 1.0;
  44977. /**
  44978. * source material index of refraction (IOR)' / 'destination material IOR.
  44979. */
  44980. _this.indexOfRefraction = 0.66;
  44981. /**
  44982. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44983. */
  44984. _this.invertRefractionY = false;
  44985. /**
  44986. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44987. * Materials half opaque for instance using refraction could benefit from this control.
  44988. */
  44989. _this.linkRefractionWithTransparency = false;
  44990. _this.useLightmapAsShadowmap = false;
  44991. /**
  44992. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44993. */
  44994. _this.useAlphaFromAlbedoTexture = false;
  44995. /**
  44996. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44997. */
  44998. _this.forceAlphaTest = false;
  44999. /**
  45000. * Defines the alpha limits in alpha test mode.
  45001. */
  45002. _this.alphaCutOff = 0.4;
  45003. /**
  45004. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45005. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45006. */
  45007. _this.useSpecularOverAlpha = true;
  45008. /**
  45009. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45010. */
  45011. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45012. /**
  45013. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45014. */
  45015. _this.useRoughnessFromMetallicTextureAlpha = true;
  45016. /**
  45017. * Specifies if the metallic texture contains the roughness information in its green channel.
  45018. */
  45019. _this.useRoughnessFromMetallicTextureGreen = false;
  45020. /**
  45021. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45022. */
  45023. _this.useMetallnessFromMetallicTextureBlue = false;
  45024. /**
  45025. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45026. */
  45027. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45028. /**
  45029. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45030. */
  45031. _this.useAmbientInGrayScale = false;
  45032. /**
  45033. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45034. * The material will try to infer what glossiness each pixel should be.
  45035. */
  45036. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45037. /**
  45038. * BJS is using an harcoded light falloff based on a manually sets up range.
  45039. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45040. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45041. */
  45042. _this.usePhysicalLightFalloff = true;
  45043. /**
  45044. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45045. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45046. */
  45047. _this.useRadianceOverAlpha = true;
  45048. /**
  45049. * Allows using an object space normal map (instead of tangent space).
  45050. */
  45051. _this.useObjectSpaceNormalMap = false;
  45052. /**
  45053. * Allows using the bump map in parallax mode.
  45054. */
  45055. _this.useParallax = false;
  45056. /**
  45057. * Allows using the bump map in parallax occlusion mode.
  45058. */
  45059. _this.useParallaxOcclusion = false;
  45060. /**
  45061. * Controls the scale bias of the parallax mode.
  45062. */
  45063. _this.parallaxScaleBias = 0.05;
  45064. /**
  45065. * If sets to true, disables all the lights affecting the material.
  45066. */
  45067. _this.disableLighting = false;
  45068. /**
  45069. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45070. */
  45071. _this.forceIrradianceInFragment = false;
  45072. /**
  45073. * Number of Simultaneous lights allowed on the material.
  45074. */
  45075. _this.maxSimultaneousLights = 4;
  45076. /**
  45077. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45078. */
  45079. _this.invertNormalMapX = false;
  45080. /**
  45081. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45082. */
  45083. _this.invertNormalMapY = false;
  45084. /**
  45085. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45086. */
  45087. _this.twoSidedLighting = false;
  45088. /**
  45089. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45090. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45091. */
  45092. _this.useAlphaFresnel = false;
  45093. /**
  45094. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45095. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45096. */
  45097. _this.useLinearAlphaFresnel = false;
  45098. /**
  45099. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45100. * And/Or occlude the blended part.
  45101. */
  45102. _this.environmentBRDFTexture = null;
  45103. /**
  45104. * Force normal to face away from face.
  45105. */
  45106. _this.forceNormalForward = false;
  45107. /**
  45108. * Enables specular anti aliasing in the PBR shader.
  45109. * It will both interacts on the Geometry for analytical and IBL lighting.
  45110. * It also prefilter the roughness map based on the bump values.
  45111. */
  45112. _this.enableSpecularAntiAliasing = false;
  45113. /**
  45114. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45115. * makes the reflect vector face the model (under horizon).
  45116. */
  45117. _this.useHorizonOcclusion = true;
  45118. /**
  45119. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45120. * too much the area relying on ambient texture to define their ambient occlusion.
  45121. */
  45122. _this.useRadianceOcclusion = true;
  45123. /**
  45124. * If set to true, no lighting calculations will be applied.
  45125. */
  45126. _this.unlit = false;
  45127. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45128. return _this;
  45129. }
  45130. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45131. /**
  45132. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45133. */
  45134. get: function () {
  45135. return this._PBRMATERIAL_OPAQUE;
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45141. /**
  45142. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45143. */
  45144. get: function () {
  45145. return this._PBRMATERIAL_ALPHATEST;
  45146. },
  45147. enumerable: true,
  45148. configurable: true
  45149. });
  45150. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45151. /**
  45152. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45153. */
  45154. get: function () {
  45155. return this._PBRMATERIAL_ALPHABLEND;
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45161. /**
  45162. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45163. * They are also discarded below the alpha cutoff threshold to improve performances.
  45164. */
  45165. get: function () {
  45166. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45167. },
  45168. enumerable: true,
  45169. configurable: true
  45170. });
  45171. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45172. /**
  45173. * Gets the image processing configuration used either in this material.
  45174. */
  45175. get: function () {
  45176. return this._imageProcessingConfiguration;
  45177. },
  45178. /**
  45179. * Sets the Default image processing configuration used either in the this material.
  45180. *
  45181. * If sets to null, the scene one is in use.
  45182. */
  45183. set: function (value) {
  45184. this._attachImageProcessingConfiguration(value);
  45185. // Ensure the effect will be rebuilt.
  45186. this._markAllSubMeshesAsTexturesDirty();
  45187. },
  45188. enumerable: true,
  45189. configurable: true
  45190. });
  45191. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45192. /**
  45193. * Gets wether the color curves effect is enabled.
  45194. */
  45195. get: function () {
  45196. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45197. },
  45198. /**
  45199. * Sets wether the color curves effect is enabled.
  45200. */
  45201. set: function (value) {
  45202. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45203. },
  45204. enumerable: true,
  45205. configurable: true
  45206. });
  45207. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45208. /**
  45209. * Gets wether the color grading effect is enabled.
  45210. */
  45211. get: function () {
  45212. return this.imageProcessingConfiguration.colorGradingEnabled;
  45213. },
  45214. /**
  45215. * Gets wether the color grading effect is enabled.
  45216. */
  45217. set: function (value) {
  45218. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45219. },
  45220. enumerable: true,
  45221. configurable: true
  45222. });
  45223. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45224. /**
  45225. * Gets wether tonemapping is enabled or not.
  45226. */
  45227. get: function () {
  45228. return this._imageProcessingConfiguration.toneMappingEnabled;
  45229. },
  45230. /**
  45231. * Sets wether tonemapping is enabled or not
  45232. */
  45233. set: function (value) {
  45234. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. ;
  45240. ;
  45241. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45242. /**
  45243. * The camera exposure used on this material.
  45244. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45245. * This corresponds to a photographic exposure.
  45246. */
  45247. get: function () {
  45248. return this._imageProcessingConfiguration.exposure;
  45249. },
  45250. /**
  45251. * The camera exposure used on this material.
  45252. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45253. * This corresponds to a photographic exposure.
  45254. */
  45255. set: function (value) {
  45256. this._imageProcessingConfiguration.exposure = value;
  45257. },
  45258. enumerable: true,
  45259. configurable: true
  45260. });
  45261. ;
  45262. ;
  45263. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45264. /**
  45265. * Gets The camera contrast used on this material.
  45266. */
  45267. get: function () {
  45268. return this._imageProcessingConfiguration.contrast;
  45269. },
  45270. /**
  45271. * Sets The camera contrast used on this material.
  45272. */
  45273. set: function (value) {
  45274. this._imageProcessingConfiguration.contrast = value;
  45275. },
  45276. enumerable: true,
  45277. configurable: true
  45278. });
  45279. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45280. /**
  45281. * Gets the Color Grading 2D Lookup Texture.
  45282. */
  45283. get: function () {
  45284. return this._imageProcessingConfiguration.colorGradingTexture;
  45285. },
  45286. /**
  45287. * Sets the Color Grading 2D Lookup Texture.
  45288. */
  45289. set: function (value) {
  45290. this._imageProcessingConfiguration.colorGradingTexture = value;
  45291. },
  45292. enumerable: true,
  45293. configurable: true
  45294. });
  45295. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45296. /**
  45297. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45298. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45299. * 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;
  45300. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45301. */
  45302. get: function () {
  45303. return this._imageProcessingConfiguration.colorCurves;
  45304. },
  45305. /**
  45306. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45307. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45308. * 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;
  45309. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45310. */
  45311. set: function (value) {
  45312. this._imageProcessingConfiguration.colorCurves = value;
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. /**
  45318. * Returns the name of this material class.
  45319. */
  45320. PBRMaterial.prototype.getClassName = function () {
  45321. return "PBRMaterial";
  45322. };
  45323. /**
  45324. * Returns an array of the actively used textures.
  45325. * @returns - Array of BaseTextures
  45326. */
  45327. PBRMaterial.prototype.getActiveTextures = function () {
  45328. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45329. if (this._albedoTexture) {
  45330. activeTextures.push(this._albedoTexture);
  45331. }
  45332. if (this._ambientTexture) {
  45333. activeTextures.push(this._ambientTexture);
  45334. }
  45335. if (this._opacityTexture) {
  45336. activeTextures.push(this._opacityTexture);
  45337. }
  45338. if (this._reflectionTexture) {
  45339. activeTextures.push(this._reflectionTexture);
  45340. }
  45341. if (this._emissiveTexture) {
  45342. activeTextures.push(this._emissiveTexture);
  45343. }
  45344. if (this._reflectivityTexture) {
  45345. activeTextures.push(this._reflectivityTexture);
  45346. }
  45347. if (this._metallicTexture) {
  45348. activeTextures.push(this._metallicTexture);
  45349. }
  45350. if (this._microSurfaceTexture) {
  45351. activeTextures.push(this._microSurfaceTexture);
  45352. }
  45353. if (this._bumpTexture) {
  45354. activeTextures.push(this._bumpTexture);
  45355. }
  45356. if (this._lightmapTexture) {
  45357. activeTextures.push(this._lightmapTexture);
  45358. }
  45359. if (this._refractionTexture) {
  45360. activeTextures.push(this._refractionTexture);
  45361. }
  45362. return activeTextures;
  45363. };
  45364. /**
  45365. * Checks to see if a texture is used in the material.
  45366. * @param texture - Base texture to use.
  45367. * @returns - Boolean specifying if a texture is used in the material.
  45368. */
  45369. PBRMaterial.prototype.hasTexture = function (texture) {
  45370. if (_super.prototype.hasTexture.call(this, texture)) {
  45371. return true;
  45372. }
  45373. if (this._albedoTexture === texture) {
  45374. return true;
  45375. }
  45376. if (this._ambientTexture === texture) {
  45377. return true;
  45378. }
  45379. if (this._opacityTexture === texture) {
  45380. return true;
  45381. }
  45382. if (this._reflectionTexture === texture) {
  45383. return true;
  45384. }
  45385. if (this._reflectivityTexture === texture) {
  45386. return true;
  45387. }
  45388. if (this._metallicTexture === texture) {
  45389. return true;
  45390. }
  45391. if (this._microSurfaceTexture === texture) {
  45392. return true;
  45393. }
  45394. if (this._bumpTexture === texture) {
  45395. return true;
  45396. }
  45397. if (this._lightmapTexture === texture) {
  45398. return true;
  45399. }
  45400. if (this._refractionTexture === texture) {
  45401. return true;
  45402. }
  45403. return false;
  45404. };
  45405. /**
  45406. * Makes a duplicate of the current material.
  45407. * @param name - name to use for the new material.
  45408. */
  45409. PBRMaterial.prototype.clone = function (name) {
  45410. var _this = this;
  45411. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45412. clone.id = name;
  45413. clone.name = name;
  45414. return clone;
  45415. };
  45416. /**
  45417. * Serializes this PBR Material.
  45418. * @returns - An object with the serialized material.
  45419. */
  45420. PBRMaterial.prototype.serialize = function () {
  45421. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45422. serializationObject.customType = "BABYLON.PBRMaterial";
  45423. return serializationObject;
  45424. };
  45425. // Statics
  45426. /**
  45427. * Parses a PBR Material from a serialized object.
  45428. * @param source - Serialized object.
  45429. * @param scene - BJS scene instance.
  45430. * @param rootUrl - url for the scene object
  45431. * @returns - PBRMaterial
  45432. */
  45433. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45434. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45435. };
  45436. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45437. /**
  45438. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45439. */
  45440. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45441. /**
  45442. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45443. */
  45444. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45445. /**
  45446. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45447. * They are also discarded below the alpha cutoff threshold to improve performances.
  45448. */
  45449. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45450. __decorate([
  45451. BABYLON.serialize(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "directIntensity", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45458. __decorate([
  45459. BABYLON.serialize(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45461. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45462. __decorate([
  45463. BABYLON.serialize(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45466. __decorate([
  45467. BABYLON.serialize(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45470. __decorate([
  45471. BABYLON.serializeAsTexture(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45474. __decorate([
  45475. BABYLON.serializeAsTexture(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45482. __decorate([
  45483. BABYLON.serializeAsTexture(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45485. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45486. __decorate([
  45487. BABYLON.serializeAsTexture(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsTexture(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsTexture(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45498. __decorate([
  45499. BABYLON.serializeAsTexture(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "metallic", void 0);
  45506. __decorate([
  45507. BABYLON.serialize(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "roughness", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsTexture(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45521. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serializeAsTexture(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45526. __decorate([
  45527. BABYLON.serializeAsColor3("ambient"),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "ambientColor", void 0);
  45530. __decorate([
  45531. BABYLON.serializeAsColor3("albedo"),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "albedoColor", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsColor3("reflectivity"),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsColor3("reflection"),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsColor3("emissive"),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45546. __decorate([
  45547. BABYLON.serialize(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "microSurface", void 0);
  45550. __decorate([
  45551. BABYLON.serialize(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45554. __decorate([
  45555. BABYLON.serialize(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45558. __decorate([
  45559. BABYLON.serialize(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45562. __decorate([
  45563. BABYLON.serialize(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45569. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45573. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45577. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useParallax", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45637. ], PBRMaterial.prototype, "disableLighting", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45645. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45666. __decorate([
  45667. BABYLON.serializeAsTexture(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45689. ], PBRMaterial.prototype, "unlit", void 0);
  45690. return PBRMaterial;
  45691. }(BABYLON.PBRBaseMaterial));
  45692. BABYLON.PBRMaterial = PBRMaterial;
  45693. })(BABYLON || (BABYLON = {}));
  45694. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45695. var BABYLON;
  45696. (function (BABYLON) {
  45697. /**
  45698. * The PBR material of BJS following the metal roughness convention.
  45699. *
  45700. * This fits to the PBR convention in the GLTF definition:
  45701. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45702. */
  45703. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45704. __extends(PBRMetallicRoughnessMaterial, _super);
  45705. /**
  45706. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45707. *
  45708. * @param name The material name
  45709. * @param scene The scene the material will be use in.
  45710. */
  45711. function PBRMetallicRoughnessMaterial(name, scene) {
  45712. var _this = _super.call(this, name, scene) || this;
  45713. _this._useRoughnessFromMetallicTextureAlpha = false;
  45714. _this._useRoughnessFromMetallicTextureGreen = true;
  45715. _this._useMetallnessFromMetallicTextureBlue = true;
  45716. _this.metallic = 1.0;
  45717. _this.roughness = 1.0;
  45718. return _this;
  45719. }
  45720. /**
  45721. * Return the currrent class name of the material.
  45722. */
  45723. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45724. return "PBRMetallicRoughnessMaterial";
  45725. };
  45726. /**
  45727. * Return the active textures of the material.
  45728. */
  45729. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45730. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45731. if (this.baseTexture) {
  45732. activeTextures.push(this.baseTexture);
  45733. }
  45734. if (this.metallicRoughnessTexture) {
  45735. activeTextures.push(this.metallicRoughnessTexture);
  45736. }
  45737. return activeTextures;
  45738. };
  45739. /**
  45740. * Checks to see if a texture is used in the material.
  45741. * @param texture - Base texture to use.
  45742. * @returns - Boolean specifying if a texture is used in the material.
  45743. */
  45744. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45745. if (_super.prototype.hasTexture.call(this, texture)) {
  45746. return true;
  45747. }
  45748. if (this.baseTexture === texture) {
  45749. return true;
  45750. }
  45751. if (this.metallicRoughnessTexture === texture) {
  45752. return true;
  45753. }
  45754. return false;
  45755. };
  45756. /**
  45757. * Makes a duplicate of the current material.
  45758. * @param name - name to use for the new material.
  45759. */
  45760. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45761. var _this = this;
  45762. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45763. clone.id = name;
  45764. clone.name = name;
  45765. return clone;
  45766. };
  45767. /**
  45768. * Serialize the material to a parsable JSON object.
  45769. */
  45770. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45772. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45773. return serializationObject;
  45774. };
  45775. /**
  45776. * Parses a JSON object correponding to the serialize function.
  45777. */
  45778. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45779. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45780. };
  45781. __decorate([
  45782. BABYLON.serializeAsColor3(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45784. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45785. __decorate([
  45786. BABYLON.serializeAsTexture(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45788. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45797. __decorate([
  45798. BABYLON.serializeAsTexture(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45800. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45801. return PBRMetallicRoughnessMaterial;
  45802. }(BABYLON.PBRBaseSimpleMaterial));
  45803. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45804. })(BABYLON || (BABYLON = {}));
  45805. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45806. var BABYLON;
  45807. (function (BABYLON) {
  45808. /**
  45809. * The PBR material of BJS following the specular glossiness convention.
  45810. *
  45811. * This fits to the PBR convention in the GLTF definition:
  45812. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45813. */
  45814. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45815. __extends(PBRSpecularGlossinessMaterial, _super);
  45816. /**
  45817. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45818. *
  45819. * @param name The material name
  45820. * @param scene The scene the material will be use in.
  45821. */
  45822. function PBRSpecularGlossinessMaterial(name, scene) {
  45823. var _this = _super.call(this, name, scene) || this;
  45824. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45825. return _this;
  45826. }
  45827. /**
  45828. * Return the currrent class name of the material.
  45829. */
  45830. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45831. return "PBRSpecularGlossinessMaterial";
  45832. };
  45833. /**
  45834. * Return the active textures of the material.
  45835. */
  45836. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45837. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45838. if (this.diffuseTexture) {
  45839. activeTextures.push(this.diffuseTexture);
  45840. }
  45841. if (this.specularGlossinessTexture) {
  45842. activeTextures.push(this.specularGlossinessTexture);
  45843. }
  45844. return activeTextures;
  45845. };
  45846. /**
  45847. * Checks to see if a texture is used in the material.
  45848. * @param texture - Base texture to use.
  45849. * @returns - Boolean specifying if a texture is used in the material.
  45850. */
  45851. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45852. if (_super.prototype.hasTexture.call(this, texture)) {
  45853. return true;
  45854. }
  45855. if (this.diffuseTexture === texture) {
  45856. return true;
  45857. }
  45858. if (this.specularGlossinessTexture === texture) {
  45859. return true;
  45860. }
  45861. return false;
  45862. };
  45863. /**
  45864. * Makes a duplicate of the current material.
  45865. * @param name - name to use for the new material.
  45866. */
  45867. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45868. var _this = this;
  45869. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45870. clone.id = name;
  45871. clone.name = name;
  45872. return clone;
  45873. };
  45874. /**
  45875. * Serialize the material to a parsable JSON object.
  45876. */
  45877. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45878. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45879. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45880. return serializationObject;
  45881. };
  45882. /**
  45883. * Parses a JSON object correponding to the serialize function.
  45884. */
  45885. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45886. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45887. };
  45888. __decorate([
  45889. BABYLON.serializeAsColor3("diffuse"),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45891. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45892. __decorate([
  45893. BABYLON.serializeAsTexture(),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45895. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45896. __decorate([
  45897. BABYLON.serializeAsColor3("specular"),
  45898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45899. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45900. __decorate([
  45901. BABYLON.serialize(),
  45902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45903. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45904. __decorate([
  45905. BABYLON.serializeAsTexture(),
  45906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45907. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45908. return PBRSpecularGlossinessMaterial;
  45909. }(BABYLON.PBRBaseSimpleMaterial));
  45910. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45911. })(BABYLON || (BABYLON = {}));
  45912. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45913. var BABYLON;
  45914. (function (BABYLON) {
  45915. BABYLON.CameraInputTypes = {};
  45916. var CameraInputsManager = /** @class */ (function () {
  45917. function CameraInputsManager(camera) {
  45918. this.attached = {};
  45919. this.camera = camera;
  45920. this.checkInputs = function () { };
  45921. }
  45922. /**
  45923. * Add an input method to a camera.
  45924. * builtin inputs example: camera.inputs.addGamepad();
  45925. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45926. * @param input camera input method
  45927. */
  45928. CameraInputsManager.prototype.add = function (input) {
  45929. var type = input.getSimpleName();
  45930. if (this.attached[type]) {
  45931. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45932. return;
  45933. }
  45934. this.attached[type] = input;
  45935. input.camera = this.camera;
  45936. //for checkInputs, we are dynamically creating a function
  45937. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45938. if (input.checkInputs) {
  45939. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45940. }
  45941. if (this.attachedElement) {
  45942. input.attachControl(this.attachedElement);
  45943. }
  45944. };
  45945. /**
  45946. * Remove a specific input method from a camera
  45947. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45948. * @param inputToRemove camera input method
  45949. */
  45950. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45951. for (var cam in this.attached) {
  45952. var input = this.attached[cam];
  45953. if (input === inputToRemove) {
  45954. input.detachControl(this.attachedElement);
  45955. input.camera = null;
  45956. delete this.attached[cam];
  45957. this.rebuildInputCheck();
  45958. }
  45959. }
  45960. };
  45961. CameraInputsManager.prototype.removeByType = function (inputType) {
  45962. for (var cam in this.attached) {
  45963. var input = this.attached[cam];
  45964. if (input.getClassName() === inputType) {
  45965. input.detachControl(this.attachedElement);
  45966. input.camera = null;
  45967. delete this.attached[cam];
  45968. this.rebuildInputCheck();
  45969. }
  45970. }
  45971. };
  45972. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45973. var current = this.checkInputs;
  45974. return function () {
  45975. current();
  45976. fn();
  45977. };
  45978. };
  45979. CameraInputsManager.prototype.attachInput = function (input) {
  45980. if (this.attachedElement) {
  45981. input.attachControl(this.attachedElement, this.noPreventDefault);
  45982. }
  45983. };
  45984. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45985. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45986. if (this.attachedElement) {
  45987. return;
  45988. }
  45989. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45990. this.attachedElement = element;
  45991. this.noPreventDefault = noPreventDefault;
  45992. for (var cam in this.attached) {
  45993. this.attached[cam].attachControl(element, noPreventDefault);
  45994. }
  45995. };
  45996. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45997. if (disconnect === void 0) { disconnect = false; }
  45998. if (this.attachedElement !== element) {
  45999. return;
  46000. }
  46001. for (var cam in this.attached) {
  46002. this.attached[cam].detachControl(element);
  46003. if (disconnect) {
  46004. this.attached[cam].camera = null;
  46005. }
  46006. }
  46007. this.attachedElement = null;
  46008. };
  46009. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46010. this.checkInputs = function () { };
  46011. for (var cam in this.attached) {
  46012. var input = this.attached[cam];
  46013. if (input.checkInputs) {
  46014. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46015. }
  46016. }
  46017. };
  46018. /**
  46019. * Remove all attached input methods from a camera
  46020. */
  46021. CameraInputsManager.prototype.clear = function () {
  46022. if (this.attachedElement) {
  46023. this.detachElement(this.attachedElement, true);
  46024. }
  46025. this.attached = {};
  46026. this.attachedElement = null;
  46027. this.checkInputs = function () { };
  46028. };
  46029. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46030. var inputs = {};
  46031. for (var cam in this.attached) {
  46032. var input = this.attached[cam];
  46033. var res = BABYLON.SerializationHelper.Serialize(input);
  46034. inputs[input.getClassName()] = res;
  46035. }
  46036. serializedCamera.inputsmgr = inputs;
  46037. };
  46038. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46039. var parsedInputs = parsedCamera.inputsmgr;
  46040. if (parsedInputs) {
  46041. this.clear();
  46042. for (var n in parsedInputs) {
  46043. var construct = BABYLON.CameraInputTypes[n];
  46044. if (construct) {
  46045. var parsedinput = parsedInputs[n];
  46046. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46047. this.add(input);
  46048. }
  46049. }
  46050. }
  46051. else {
  46052. //2016-03-08 this part is for managing backward compatibility
  46053. for (var n in this.attached) {
  46054. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46055. if (construct) {
  46056. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46057. this.remove(this.attached[n]);
  46058. this.add(input);
  46059. }
  46060. }
  46061. }
  46062. };
  46063. return CameraInputsManager;
  46064. }());
  46065. BABYLON.CameraInputsManager = CameraInputsManager;
  46066. })(BABYLON || (BABYLON = {}));
  46067. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46068. var BABYLON;
  46069. (function (BABYLON) {
  46070. var TargetCamera = /** @class */ (function (_super) {
  46071. __extends(TargetCamera, _super);
  46072. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46073. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46074. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46075. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46076. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46077. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46078. _this.speed = 2.0;
  46079. _this.noRotationConstraint = false;
  46080. _this.lockedTarget = null;
  46081. _this._currentTarget = BABYLON.Vector3.Zero();
  46082. _this._viewMatrix = BABYLON.Matrix.Zero();
  46083. _this._camMatrix = BABYLON.Matrix.Zero();
  46084. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46085. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46086. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46087. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46088. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46089. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46090. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46091. return _this;
  46092. }
  46093. TargetCamera.prototype.getFrontPosition = function (distance) {
  46094. this.getWorldMatrix();
  46095. var direction = this.getTarget().subtract(this.position);
  46096. direction.normalize();
  46097. direction.scaleInPlace(distance);
  46098. return this.globalPosition.add(direction);
  46099. };
  46100. TargetCamera.prototype._getLockedTargetPosition = function () {
  46101. if (!this.lockedTarget) {
  46102. return null;
  46103. }
  46104. if (this.lockedTarget.absolutePosition) {
  46105. this.lockedTarget.computeWorldMatrix();
  46106. }
  46107. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46108. };
  46109. TargetCamera.prototype.storeState = function () {
  46110. this._storedPosition = this.position.clone();
  46111. this._storedRotation = this.rotation.clone();
  46112. if (this.rotationQuaternion) {
  46113. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46114. }
  46115. return _super.prototype.storeState.call(this);
  46116. };
  46117. /**
  46118. * Restored camera state. You must call storeState() first
  46119. */
  46120. TargetCamera.prototype._restoreStateValues = function () {
  46121. if (!_super.prototype._restoreStateValues.call(this)) {
  46122. return false;
  46123. }
  46124. this.position = this._storedPosition.clone();
  46125. this.rotation = this._storedRotation.clone();
  46126. if (this.rotationQuaternion) {
  46127. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46128. }
  46129. this.cameraDirection.copyFromFloats(0, 0, 0);
  46130. this.cameraRotation.copyFromFloats(0, 0);
  46131. return true;
  46132. };
  46133. // Cache
  46134. TargetCamera.prototype._initCache = function () {
  46135. _super.prototype._initCache.call(this);
  46136. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46137. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46138. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46139. };
  46140. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46141. if (!ignoreParentClass) {
  46142. _super.prototype._updateCache.call(this);
  46143. }
  46144. var lockedTargetPosition = this._getLockedTargetPosition();
  46145. if (!lockedTargetPosition) {
  46146. this._cache.lockedTarget = null;
  46147. }
  46148. else {
  46149. if (!this._cache.lockedTarget) {
  46150. this._cache.lockedTarget = lockedTargetPosition.clone();
  46151. }
  46152. else {
  46153. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46154. }
  46155. }
  46156. this._cache.rotation.copyFrom(this.rotation);
  46157. if (this.rotationQuaternion)
  46158. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46159. };
  46160. // Synchronized
  46161. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46162. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46163. return false;
  46164. }
  46165. var lockedTargetPosition = this._getLockedTargetPosition();
  46166. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46167. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46168. };
  46169. // Methods
  46170. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46171. var engine = this.getEngine();
  46172. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46173. };
  46174. // Target
  46175. TargetCamera.prototype.setTarget = function (target) {
  46176. this.upVector.normalize();
  46177. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46178. this._camMatrix.invert();
  46179. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46180. var vDir = target.subtract(this.position);
  46181. if (vDir.x >= 0.0) {
  46182. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46183. }
  46184. else {
  46185. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46186. }
  46187. this.rotation.z = 0;
  46188. if (isNaN(this.rotation.x)) {
  46189. this.rotation.x = 0;
  46190. }
  46191. if (isNaN(this.rotation.y)) {
  46192. this.rotation.y = 0;
  46193. }
  46194. if (isNaN(this.rotation.z)) {
  46195. this.rotation.z = 0;
  46196. }
  46197. if (this.rotationQuaternion) {
  46198. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46199. }
  46200. };
  46201. /**
  46202. * Return the current target position of the camera. This value is expressed in local space.
  46203. */
  46204. TargetCamera.prototype.getTarget = function () {
  46205. return this._currentTarget;
  46206. };
  46207. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46208. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46209. };
  46210. TargetCamera.prototype._updatePosition = function () {
  46211. if (this.parent) {
  46212. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46213. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46214. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46215. return;
  46216. }
  46217. this.position.addInPlace(this.cameraDirection);
  46218. };
  46219. TargetCamera.prototype._checkInputs = function () {
  46220. var needToMove = this._decideIfNeedsToMove();
  46221. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46222. // Move
  46223. if (needToMove) {
  46224. this._updatePosition();
  46225. }
  46226. // Rotate
  46227. if (needToRotate) {
  46228. this.rotation.x += this.cameraRotation.x;
  46229. this.rotation.y += this.cameraRotation.y;
  46230. //rotate, if quaternion is set and rotation was used
  46231. if (this.rotationQuaternion) {
  46232. var len = this.rotation.lengthSquared();
  46233. if (len) {
  46234. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46235. }
  46236. }
  46237. if (!this.noRotationConstraint) {
  46238. var limit = (Math.PI / 2) * 0.95;
  46239. if (this.rotation.x > limit)
  46240. this.rotation.x = limit;
  46241. if (this.rotation.x < -limit)
  46242. this.rotation.x = -limit;
  46243. }
  46244. }
  46245. // Inertia
  46246. if (needToMove) {
  46247. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46248. this.cameraDirection.x = 0;
  46249. }
  46250. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46251. this.cameraDirection.y = 0;
  46252. }
  46253. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46254. this.cameraDirection.z = 0;
  46255. }
  46256. this.cameraDirection.scaleInPlace(this.inertia);
  46257. }
  46258. if (needToRotate) {
  46259. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46260. this.cameraRotation.x = 0;
  46261. }
  46262. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46263. this.cameraRotation.y = 0;
  46264. }
  46265. this.cameraRotation.scaleInPlace(this.inertia);
  46266. }
  46267. _super.prototype._checkInputs.call(this);
  46268. };
  46269. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46270. if (this.rotationQuaternion) {
  46271. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46272. }
  46273. else {
  46274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46275. }
  46276. //update the up vector!
  46277. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46278. };
  46279. TargetCamera.prototype._getViewMatrix = function () {
  46280. if (this.lockedTarget) {
  46281. this.setTarget(this._getLockedTargetPosition());
  46282. }
  46283. // Compute
  46284. this._updateCameraRotationMatrix();
  46285. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46286. // Computing target and final matrix
  46287. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46288. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46289. return this._viewMatrix;
  46290. };
  46291. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46292. if (this.parent) {
  46293. var parentWorldMatrix = this.parent.getWorldMatrix();
  46294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46295. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46296. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46297. this._markSyncedWithParent();
  46298. }
  46299. else {
  46300. this._globalPosition.copyFrom(this.position);
  46301. this._globalCurrentTarget.copyFrom(target);
  46302. this._globalCurrentUpVector.copyFrom(up);
  46303. }
  46304. if (this.getScene().useRightHandedSystem) {
  46305. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46306. }
  46307. else {
  46308. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46309. }
  46310. };
  46311. /**
  46312. * @override
  46313. * Override Camera.createRigCamera
  46314. */
  46315. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46316. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46317. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46318. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46319. if (!this.rotationQuaternion) {
  46320. this.rotationQuaternion = new BABYLON.Quaternion();
  46321. }
  46322. rigCamera._cameraRigParams = {};
  46323. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46324. }
  46325. return rigCamera;
  46326. }
  46327. return null;
  46328. };
  46329. /**
  46330. * @override
  46331. * Override Camera._updateRigCameras
  46332. */
  46333. TargetCamera.prototype._updateRigCameras = function () {
  46334. var camLeft = this._rigCameras[0];
  46335. var camRight = this._rigCameras[1];
  46336. switch (this.cameraRigMode) {
  46337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46341. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46342. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46343. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46344. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46345. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46346. camLeft.setTarget(this.getTarget());
  46347. camRight.setTarget(this.getTarget());
  46348. break;
  46349. case BABYLON.Camera.RIG_MODE_VR:
  46350. if (camLeft.rotationQuaternion) {
  46351. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46352. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46353. }
  46354. else {
  46355. camLeft.rotation.copyFrom(this.rotation);
  46356. camRight.rotation.copyFrom(this.rotation);
  46357. }
  46358. camLeft.position.copyFrom(this.position);
  46359. camRight.position.copyFrom(this.position);
  46360. break;
  46361. }
  46362. _super.prototype._updateRigCameras.call(this);
  46363. };
  46364. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46365. if (!this._rigCamTransformMatrix) {
  46366. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46367. }
  46368. var target = this.getTarget();
  46369. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46370. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46371. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46372. };
  46373. TargetCamera.prototype.getClassName = function () {
  46374. return "TargetCamera";
  46375. };
  46376. __decorate([
  46377. BABYLON.serializeAsVector3()
  46378. ], TargetCamera.prototype, "rotation", void 0);
  46379. __decorate([
  46380. BABYLON.serialize()
  46381. ], TargetCamera.prototype, "speed", void 0);
  46382. __decorate([
  46383. BABYLON.serializeAsMeshReference("lockedTargetId")
  46384. ], TargetCamera.prototype, "lockedTarget", void 0);
  46385. return TargetCamera;
  46386. }(BABYLON.Camera));
  46387. BABYLON.TargetCamera = TargetCamera;
  46388. })(BABYLON || (BABYLON = {}));
  46389. //# sourceMappingURL=babylon.targetCamera.js.map
  46390. var BABYLON;
  46391. (function (BABYLON) {
  46392. var FreeCameraMouseInput = /** @class */ (function () {
  46393. function FreeCameraMouseInput(touchEnabled) {
  46394. if (touchEnabled === void 0) { touchEnabled = true; }
  46395. this.touchEnabled = touchEnabled;
  46396. this.buttons = [0, 1, 2];
  46397. this.angularSensibility = 2000.0;
  46398. this.previousPosition = null;
  46399. }
  46400. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46401. var _this = this;
  46402. var engine = this.camera.getEngine();
  46403. if (!this._pointerInput) {
  46404. this._pointerInput = function (p, s) {
  46405. var evt = p.event;
  46406. if (engine.isInVRExclusivePointerMode) {
  46407. return;
  46408. }
  46409. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46410. return;
  46411. }
  46412. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46413. return;
  46414. }
  46415. var srcElement = (evt.srcElement || evt.target);
  46416. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46417. try {
  46418. srcElement.setPointerCapture(evt.pointerId);
  46419. }
  46420. catch (e) {
  46421. //Nothing to do with the error. Execution will continue.
  46422. }
  46423. _this.previousPosition = {
  46424. x: evt.clientX,
  46425. y: evt.clientY
  46426. };
  46427. if (!noPreventDefault) {
  46428. evt.preventDefault();
  46429. element.focus();
  46430. }
  46431. }
  46432. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46433. try {
  46434. srcElement.releasePointerCapture(evt.pointerId);
  46435. }
  46436. catch (e) {
  46437. //Nothing to do with the error.
  46438. }
  46439. _this.previousPosition = null;
  46440. if (!noPreventDefault) {
  46441. evt.preventDefault();
  46442. }
  46443. }
  46444. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46445. if (!_this.previousPosition || engine.isPointerLock) {
  46446. return;
  46447. }
  46448. var offsetX = evt.clientX - _this.previousPosition.x;
  46449. if (_this.camera.getScene().useRightHandedSystem)
  46450. offsetX *= -1;
  46451. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46452. offsetX *= -1;
  46453. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46454. var offsetY = evt.clientY - _this.previousPosition.y;
  46455. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46456. _this.previousPosition = {
  46457. x: evt.clientX,
  46458. y: evt.clientY
  46459. };
  46460. if (!noPreventDefault) {
  46461. evt.preventDefault();
  46462. }
  46463. }
  46464. };
  46465. }
  46466. this._onMouseMove = function (evt) {
  46467. if (!engine.isPointerLock) {
  46468. return;
  46469. }
  46470. if (engine.isInVRExclusivePointerMode) {
  46471. return;
  46472. }
  46473. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46474. if (_this.camera.getScene().useRightHandedSystem)
  46475. offsetX *= -1;
  46476. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46477. offsetX *= -1;
  46478. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46479. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46480. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46481. _this.previousPosition = null;
  46482. if (!noPreventDefault) {
  46483. evt.preventDefault();
  46484. }
  46485. };
  46486. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46487. element.addEventListener("mousemove", this._onMouseMove, false);
  46488. };
  46489. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46490. if (this._observer && element) {
  46491. this.camera.getScene().onPointerObservable.remove(this._observer);
  46492. if (this._onMouseMove) {
  46493. element.removeEventListener("mousemove", this._onMouseMove);
  46494. }
  46495. this._observer = null;
  46496. this._onMouseMove = null;
  46497. this.previousPosition = null;
  46498. }
  46499. };
  46500. FreeCameraMouseInput.prototype.getClassName = function () {
  46501. return "FreeCameraMouseInput";
  46502. };
  46503. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46504. return "mouse";
  46505. };
  46506. __decorate([
  46507. BABYLON.serialize()
  46508. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46509. __decorate([
  46510. BABYLON.serialize()
  46511. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46512. return FreeCameraMouseInput;
  46513. }());
  46514. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46515. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46516. })(BABYLON || (BABYLON = {}));
  46517. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46518. var BABYLON;
  46519. (function (BABYLON) {
  46520. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46521. function FreeCameraKeyboardMoveInput() {
  46522. this._keys = new Array();
  46523. this.keysUp = [38];
  46524. this.keysDown = [40];
  46525. this.keysLeft = [37];
  46526. this.keysRight = [39];
  46527. }
  46528. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46529. var _this = this;
  46530. if (this._onCanvasBlurObserver) {
  46531. return;
  46532. }
  46533. this._scene = this.camera.getScene();
  46534. this._engine = this._scene.getEngine();
  46535. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46536. _this._keys = [];
  46537. });
  46538. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46539. var evt = info.event;
  46540. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46541. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46542. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46543. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46544. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46545. var index = _this._keys.indexOf(evt.keyCode);
  46546. if (index === -1) {
  46547. _this._keys.push(evt.keyCode);
  46548. }
  46549. if (!noPreventDefault) {
  46550. evt.preventDefault();
  46551. }
  46552. }
  46553. }
  46554. else {
  46555. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46556. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46557. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46558. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46559. var index = _this._keys.indexOf(evt.keyCode);
  46560. if (index >= 0) {
  46561. _this._keys.splice(index, 1);
  46562. }
  46563. if (!noPreventDefault) {
  46564. evt.preventDefault();
  46565. }
  46566. }
  46567. }
  46568. });
  46569. };
  46570. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46571. if (this._scene) {
  46572. if (this._onKeyboardObserver) {
  46573. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46574. }
  46575. if (this._onCanvasBlurObserver) {
  46576. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46577. }
  46578. this._onKeyboardObserver = null;
  46579. this._onCanvasBlurObserver = null;
  46580. }
  46581. this._keys = [];
  46582. };
  46583. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46584. if (this._onKeyboardObserver) {
  46585. var camera = this.camera;
  46586. // Keyboard
  46587. for (var index = 0; index < this._keys.length; index++) {
  46588. var keyCode = this._keys[index];
  46589. var speed = camera._computeLocalCameraSpeed();
  46590. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46591. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46592. }
  46593. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46594. camera._localDirection.copyFromFloats(0, 0, speed);
  46595. }
  46596. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46597. camera._localDirection.copyFromFloats(speed, 0, 0);
  46598. }
  46599. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46600. camera._localDirection.copyFromFloats(0, 0, -speed);
  46601. }
  46602. if (camera.getScene().useRightHandedSystem) {
  46603. camera._localDirection.z *= -1;
  46604. }
  46605. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46606. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46607. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46608. }
  46609. }
  46610. };
  46611. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46612. return "FreeCameraKeyboardMoveInput";
  46613. };
  46614. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46615. this._keys = [];
  46616. };
  46617. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46618. return "keyboard";
  46619. };
  46620. __decorate([
  46621. BABYLON.serialize()
  46622. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46623. __decorate([
  46624. BABYLON.serialize()
  46625. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46626. __decorate([
  46627. BABYLON.serialize()
  46628. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46629. __decorate([
  46630. BABYLON.serialize()
  46631. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46632. return FreeCameraKeyboardMoveInput;
  46633. }());
  46634. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46635. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46636. })(BABYLON || (BABYLON = {}));
  46637. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46638. var BABYLON;
  46639. (function (BABYLON) {
  46640. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46641. __extends(FreeCameraInputsManager, _super);
  46642. function FreeCameraInputsManager(camera) {
  46643. return _super.call(this, camera) || this;
  46644. }
  46645. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46646. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46647. return this;
  46648. };
  46649. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46650. if (touchEnabled === void 0) { touchEnabled = true; }
  46651. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46652. return this;
  46653. };
  46654. FreeCameraInputsManager.prototype.addGamepad = function () {
  46655. this.add(new BABYLON.FreeCameraGamepadInput());
  46656. return this;
  46657. };
  46658. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46659. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46660. return this;
  46661. };
  46662. FreeCameraInputsManager.prototype.addTouch = function () {
  46663. this.add(new BABYLON.FreeCameraTouchInput());
  46664. return this;
  46665. };
  46666. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46667. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46668. return this;
  46669. };
  46670. return FreeCameraInputsManager;
  46671. }(BABYLON.CameraInputsManager));
  46672. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46673. })(BABYLON || (BABYLON = {}));
  46674. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46675. var BABYLON;
  46676. (function (BABYLON) {
  46677. var FreeCamera = /** @class */ (function (_super) {
  46678. __extends(FreeCamera, _super);
  46679. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46680. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46681. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46682. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46683. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46684. _this.checkCollisions = false;
  46685. _this.applyGravity = false;
  46686. _this._needMoveForGravity = false;
  46687. _this._oldPosition = BABYLON.Vector3.Zero();
  46688. _this._diffPosition = BABYLON.Vector3.Zero();
  46689. _this._newPosition = BABYLON.Vector3.Zero();
  46690. // Collisions
  46691. _this._collisionMask = -1;
  46692. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46693. if (collidedMesh === void 0) { collidedMesh = null; }
  46694. //TODO move this to the collision coordinator!
  46695. if (_this.getScene().workerCollisions)
  46696. newPosition.multiplyInPlace(_this._collider._radius);
  46697. var updatePosition = function (newPos) {
  46698. _this._newPosition.copyFrom(newPos);
  46699. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46700. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46701. _this.position.addInPlace(_this._diffPosition);
  46702. if (_this.onCollide && collidedMesh) {
  46703. _this.onCollide(collidedMesh);
  46704. }
  46705. }
  46706. };
  46707. updatePosition(newPosition);
  46708. };
  46709. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46710. _this.inputs.addKeyboard().addMouse();
  46711. return _this;
  46712. }
  46713. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46714. //-- begin properties for backward compatibility for inputs
  46715. /**
  46716. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46717. * Higher values reduce sensitivity.
  46718. */
  46719. get: function () {
  46720. var mouse = this.inputs.attached["mouse"];
  46721. if (mouse)
  46722. return mouse.angularSensibility;
  46723. return 0;
  46724. },
  46725. /**
  46726. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46727. * Higher values reduce sensitivity.
  46728. */
  46729. set: function (value) {
  46730. var mouse = this.inputs.attached["mouse"];
  46731. if (mouse)
  46732. mouse.angularSensibility = value;
  46733. },
  46734. enumerable: true,
  46735. configurable: true
  46736. });
  46737. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46738. get: function () {
  46739. var keyboard = this.inputs.attached["keyboard"];
  46740. if (keyboard)
  46741. return keyboard.keysUp;
  46742. return [];
  46743. },
  46744. set: function (value) {
  46745. var keyboard = this.inputs.attached["keyboard"];
  46746. if (keyboard)
  46747. keyboard.keysUp = value;
  46748. },
  46749. enumerable: true,
  46750. configurable: true
  46751. });
  46752. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46753. get: function () {
  46754. var keyboard = this.inputs.attached["keyboard"];
  46755. if (keyboard)
  46756. return keyboard.keysDown;
  46757. return [];
  46758. },
  46759. set: function (value) {
  46760. var keyboard = this.inputs.attached["keyboard"];
  46761. if (keyboard)
  46762. keyboard.keysDown = value;
  46763. },
  46764. enumerable: true,
  46765. configurable: true
  46766. });
  46767. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46768. get: function () {
  46769. var keyboard = this.inputs.attached["keyboard"];
  46770. if (keyboard)
  46771. return keyboard.keysLeft;
  46772. return [];
  46773. },
  46774. set: function (value) {
  46775. var keyboard = this.inputs.attached["keyboard"];
  46776. if (keyboard)
  46777. keyboard.keysLeft = value;
  46778. },
  46779. enumerable: true,
  46780. configurable: true
  46781. });
  46782. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46783. get: function () {
  46784. var keyboard = this.inputs.attached["keyboard"];
  46785. if (keyboard)
  46786. return keyboard.keysRight;
  46787. return [];
  46788. },
  46789. set: function (value) {
  46790. var keyboard = this.inputs.attached["keyboard"];
  46791. if (keyboard)
  46792. keyboard.keysRight = value;
  46793. },
  46794. enumerable: true,
  46795. configurable: true
  46796. });
  46797. // Controls
  46798. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46799. this.inputs.attachElement(element, noPreventDefault);
  46800. };
  46801. FreeCamera.prototype.detachControl = function (element) {
  46802. this.inputs.detachElement(element);
  46803. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46804. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46805. };
  46806. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46807. get: function () {
  46808. return this._collisionMask;
  46809. },
  46810. set: function (mask) {
  46811. this._collisionMask = !isNaN(mask) ? mask : -1;
  46812. },
  46813. enumerable: true,
  46814. configurable: true
  46815. });
  46816. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46817. var globalPosition;
  46818. if (this.parent) {
  46819. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46820. }
  46821. else {
  46822. globalPosition = this.position;
  46823. }
  46824. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46825. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46826. if (!this._collider) {
  46827. this._collider = new BABYLON.Collider();
  46828. }
  46829. this._collider._radius = this.ellipsoid;
  46830. this._collider.collisionMask = this._collisionMask;
  46831. //no need for clone, as long as gravity is not on.
  46832. var actualDisplacement = displacement;
  46833. //add gravity to the direction to prevent the dual-collision checking
  46834. if (this.applyGravity) {
  46835. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46836. actualDisplacement = displacement.add(this.getScene().gravity);
  46837. }
  46838. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46839. };
  46840. FreeCamera.prototype._checkInputs = function () {
  46841. if (!this._localDirection) {
  46842. this._localDirection = BABYLON.Vector3.Zero();
  46843. this._transformedDirection = BABYLON.Vector3.Zero();
  46844. }
  46845. this.inputs.checkInputs();
  46846. _super.prototype._checkInputs.call(this);
  46847. };
  46848. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46849. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46850. };
  46851. FreeCamera.prototype._updatePosition = function () {
  46852. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46853. this._collideWithWorld(this.cameraDirection);
  46854. }
  46855. else {
  46856. _super.prototype._updatePosition.call(this);
  46857. }
  46858. };
  46859. FreeCamera.prototype.dispose = function () {
  46860. this.inputs.clear();
  46861. _super.prototype.dispose.call(this);
  46862. };
  46863. FreeCamera.prototype.getClassName = function () {
  46864. return "FreeCamera";
  46865. };
  46866. __decorate([
  46867. BABYLON.serializeAsVector3()
  46868. ], FreeCamera.prototype, "ellipsoid", void 0);
  46869. __decorate([
  46870. BABYLON.serializeAsVector3()
  46871. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46872. __decorate([
  46873. BABYLON.serialize()
  46874. ], FreeCamera.prototype, "checkCollisions", void 0);
  46875. __decorate([
  46876. BABYLON.serialize()
  46877. ], FreeCamera.prototype, "applyGravity", void 0);
  46878. return FreeCamera;
  46879. }(BABYLON.TargetCamera));
  46880. BABYLON.FreeCamera = FreeCamera;
  46881. })(BABYLON || (BABYLON = {}));
  46882. //# sourceMappingURL=babylon.freeCamera.js.map
  46883. var BABYLON;
  46884. (function (BABYLON) {
  46885. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46886. function ArcRotateCameraKeyboardMoveInput() {
  46887. this._keys = new Array();
  46888. this.keysUp = [38];
  46889. this.keysDown = [40];
  46890. this.keysLeft = [37];
  46891. this.keysRight = [39];
  46892. this.keysReset = [220];
  46893. this.panningSensibility = 50.0;
  46894. this.zoomingSensibility = 25.0;
  46895. this.useAltToZoom = true;
  46896. }
  46897. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46898. var _this = this;
  46899. if (this._onCanvasBlurObserver) {
  46900. return;
  46901. }
  46902. this._scene = this.camera.getScene();
  46903. this._engine = this._scene.getEngine();
  46904. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46905. _this._keys = [];
  46906. });
  46907. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46908. var evt = info.event;
  46909. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46910. _this._ctrlPressed = evt.ctrlKey;
  46911. _this._altPressed = evt.altKey;
  46912. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46913. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46914. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46915. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46916. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46917. var index = _this._keys.indexOf(evt.keyCode);
  46918. if (index === -1) {
  46919. _this._keys.push(evt.keyCode);
  46920. }
  46921. if (evt.preventDefault) {
  46922. if (!noPreventDefault) {
  46923. evt.preventDefault();
  46924. }
  46925. }
  46926. }
  46927. }
  46928. else {
  46929. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46930. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46931. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46932. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46933. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46934. var index = _this._keys.indexOf(evt.keyCode);
  46935. if (index >= 0) {
  46936. _this._keys.splice(index, 1);
  46937. }
  46938. if (evt.preventDefault) {
  46939. if (!noPreventDefault) {
  46940. evt.preventDefault();
  46941. }
  46942. }
  46943. }
  46944. }
  46945. });
  46946. };
  46947. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46948. if (this._scene) {
  46949. if (this._onKeyboardObserver) {
  46950. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46951. }
  46952. if (this._onCanvasBlurObserver) {
  46953. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46954. }
  46955. this._onKeyboardObserver = null;
  46956. this._onCanvasBlurObserver = null;
  46957. }
  46958. this._keys = [];
  46959. };
  46960. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46961. if (this._onKeyboardObserver) {
  46962. var camera = this.camera;
  46963. for (var index = 0; index < this._keys.length; index++) {
  46964. var keyCode = this._keys[index];
  46965. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46966. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46967. camera.inertialPanningX -= 1 / this.panningSensibility;
  46968. }
  46969. else {
  46970. camera.inertialAlphaOffset -= 0.01;
  46971. }
  46972. }
  46973. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46974. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46975. camera.inertialPanningY += 1 / this.panningSensibility;
  46976. }
  46977. else if (this._altPressed && this.useAltToZoom) {
  46978. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46979. }
  46980. else {
  46981. camera.inertialBetaOffset -= 0.01;
  46982. }
  46983. }
  46984. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46985. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46986. camera.inertialPanningX += 1 / this.panningSensibility;
  46987. }
  46988. else {
  46989. camera.inertialAlphaOffset += 0.01;
  46990. }
  46991. }
  46992. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46993. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46994. camera.inertialPanningY -= 1 / this.panningSensibility;
  46995. }
  46996. else if (this._altPressed && this.useAltToZoom) {
  46997. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46998. }
  46999. else {
  47000. camera.inertialBetaOffset += 0.01;
  47001. }
  47002. }
  47003. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47004. camera.restoreState();
  47005. }
  47006. }
  47007. }
  47008. };
  47009. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47010. return "ArcRotateCameraKeyboardMoveInput";
  47011. };
  47012. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47013. return "keyboard";
  47014. };
  47015. __decorate([
  47016. BABYLON.serialize()
  47017. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47018. __decorate([
  47019. BABYLON.serialize()
  47020. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47021. __decorate([
  47022. BABYLON.serialize()
  47023. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47024. __decorate([
  47025. BABYLON.serialize()
  47026. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47027. __decorate([
  47028. BABYLON.serialize()
  47029. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47030. __decorate([
  47031. BABYLON.serialize()
  47032. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47033. __decorate([
  47034. BABYLON.serialize()
  47035. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47036. __decorate([
  47037. BABYLON.serialize()
  47038. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47039. return ArcRotateCameraKeyboardMoveInput;
  47040. }());
  47041. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47042. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47043. })(BABYLON || (BABYLON = {}));
  47044. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47045. var BABYLON;
  47046. (function (BABYLON) {
  47047. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47048. function ArcRotateCameraMouseWheelInput() {
  47049. this.wheelPrecision = 3.0;
  47050. /**
  47051. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47052. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47053. */
  47054. this.wheelDeltaPercentage = 0;
  47055. }
  47056. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47057. var _this = this;
  47058. this._wheel = function (p, s) {
  47059. //sanity check - this should be a PointerWheel event.
  47060. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47061. return;
  47062. var event = p.event;
  47063. var delta = 0;
  47064. if (event.wheelDelta) {
  47065. if (_this.wheelDeltaPercentage) {
  47066. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47067. if (event.wheelDelta > 0) {
  47068. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47069. }
  47070. else {
  47071. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47072. }
  47073. }
  47074. else {
  47075. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47076. }
  47077. }
  47078. else if (event.detail) {
  47079. delta = -event.detail / _this.wheelPrecision;
  47080. }
  47081. if (delta)
  47082. _this.camera.inertialRadiusOffset += delta;
  47083. if (event.preventDefault) {
  47084. if (!noPreventDefault) {
  47085. event.preventDefault();
  47086. }
  47087. }
  47088. };
  47089. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47090. };
  47091. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47092. if (this._observer && element) {
  47093. this.camera.getScene().onPointerObservable.remove(this._observer);
  47094. this._observer = null;
  47095. this._wheel = null;
  47096. }
  47097. };
  47098. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47099. return "ArcRotateCameraMouseWheelInput";
  47100. };
  47101. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47102. return "mousewheel";
  47103. };
  47104. __decorate([
  47105. BABYLON.serialize()
  47106. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47107. __decorate([
  47108. BABYLON.serialize()
  47109. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47110. return ArcRotateCameraMouseWheelInput;
  47111. }());
  47112. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47113. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47114. })(BABYLON || (BABYLON = {}));
  47115. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47116. var BABYLON;
  47117. (function (BABYLON) {
  47118. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47119. function ArcRotateCameraPointersInput() {
  47120. this.buttons = [0, 1, 2];
  47121. this.angularSensibilityX = 1000.0;
  47122. this.angularSensibilityY = 1000.0;
  47123. this.pinchPrecision = 12.0;
  47124. /**
  47125. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47126. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47127. */
  47128. this.pinchDeltaPercentage = 0;
  47129. this.panningSensibility = 1000.0;
  47130. this.multiTouchPanning = true;
  47131. this.multiTouchPanAndZoom = true;
  47132. this._isPanClick = false;
  47133. this.pinchInwards = true;
  47134. }
  47135. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47136. var _this = this;
  47137. var engine = this.camera.getEngine();
  47138. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47139. var pointA = null;
  47140. var pointB = null;
  47141. var previousPinchSquaredDistance = 0;
  47142. var initialDistance = 0;
  47143. var twoFingerActivityCount = 0;
  47144. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47145. this._pointerInput = function (p, s) {
  47146. var evt = p.event;
  47147. var isTouch = p.event.pointerType === "touch";
  47148. if (engine.isInVRExclusivePointerMode) {
  47149. return;
  47150. }
  47151. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47152. return;
  47153. }
  47154. var srcElement = (evt.srcElement || evt.target);
  47155. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47156. try {
  47157. srcElement.setPointerCapture(evt.pointerId);
  47158. }
  47159. catch (e) {
  47160. //Nothing to do with the error. Execution will continue.
  47161. }
  47162. // Manage panning with pan button click
  47163. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47164. // manage pointers
  47165. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47166. if (pointA === null) {
  47167. pointA = cacheSoloPointer;
  47168. }
  47169. else if (pointB === null) {
  47170. pointB = cacheSoloPointer;
  47171. }
  47172. if (!noPreventDefault) {
  47173. evt.preventDefault();
  47174. element.focus();
  47175. }
  47176. }
  47177. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47178. _this.camera.restoreState();
  47179. }
  47180. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47181. try {
  47182. srcElement.releasePointerCapture(evt.pointerId);
  47183. }
  47184. catch (e) {
  47185. //Nothing to do with the error.
  47186. }
  47187. cacheSoloPointer = null;
  47188. previousPinchSquaredDistance = 0;
  47189. previousMultiTouchPanPosition.isPaning = false;
  47190. previousMultiTouchPanPosition.isPinching = false;
  47191. twoFingerActivityCount = 0;
  47192. initialDistance = 0;
  47193. if (!isTouch) {
  47194. pointB = null; // Mouse and pen are mono pointer
  47195. }
  47196. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47197. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47198. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47199. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47200. if (engine._badOS) {
  47201. pointA = pointB = null;
  47202. }
  47203. else {
  47204. //only remove the impacted pointer in case of multitouch allowing on most
  47205. //platforms switching from rotate to zoom and pan seamlessly.
  47206. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47207. pointA = pointB;
  47208. pointB = null;
  47209. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47210. }
  47211. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47212. pointB = null;
  47213. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47214. }
  47215. else {
  47216. pointA = pointB = null;
  47217. }
  47218. }
  47219. if (!noPreventDefault) {
  47220. evt.preventDefault();
  47221. }
  47222. }
  47223. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47224. if (!noPreventDefault) {
  47225. evt.preventDefault();
  47226. }
  47227. // One button down
  47228. if (pointA && pointB === null && cacheSoloPointer) {
  47229. if (_this.panningSensibility !== 0 &&
  47230. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47231. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47232. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47233. }
  47234. else {
  47235. var offsetX = evt.clientX - cacheSoloPointer.x;
  47236. var offsetY = evt.clientY - cacheSoloPointer.y;
  47237. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47238. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47239. }
  47240. cacheSoloPointer.x = evt.clientX;
  47241. cacheSoloPointer.y = evt.clientY;
  47242. }
  47243. // Two buttons down: pinch/pan
  47244. else if (pointA && pointB) {
  47245. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47246. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47247. ed.x = evt.clientX;
  47248. ed.y = evt.clientY;
  47249. var direction = _this.pinchInwards ? 1 : -1;
  47250. var distX = pointA.x - pointB.x;
  47251. var distY = pointA.y - pointB.y;
  47252. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47253. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47254. if (previousPinchSquaredDistance === 0) {
  47255. initialDistance = pinchDistance;
  47256. previousPinchSquaredDistance = pinchSquaredDistance;
  47257. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47258. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47259. return;
  47260. }
  47261. if (_this.multiTouchPanAndZoom) {
  47262. if (_this.pinchDeltaPercentage) {
  47263. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47264. }
  47265. else {
  47266. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47267. (_this.pinchPrecision *
  47268. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47269. direction);
  47270. }
  47271. if (_this.panningSensibility !== 0) {
  47272. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47273. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47274. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47275. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47276. previousMultiTouchPanPosition.x = pointersCenterX;
  47277. previousMultiTouchPanPosition.y = pointersCenterY;
  47278. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47279. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47280. }
  47281. }
  47282. else {
  47283. twoFingerActivityCount++;
  47284. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47285. if (_this.pinchDeltaPercentage) {
  47286. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47287. }
  47288. else {
  47289. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47290. (_this.pinchPrecision *
  47291. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47292. direction);
  47293. }
  47294. previousMultiTouchPanPosition.isPaning = false;
  47295. previousMultiTouchPanPosition.isPinching = true;
  47296. }
  47297. else {
  47298. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47299. if (!previousMultiTouchPanPosition.isPaning) {
  47300. previousMultiTouchPanPosition.isPaning = true;
  47301. previousMultiTouchPanPosition.isPinching = false;
  47302. previousMultiTouchPanPosition.x = ed.x;
  47303. previousMultiTouchPanPosition.y = ed.y;
  47304. return;
  47305. }
  47306. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47307. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47308. }
  47309. }
  47310. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47311. previousMultiTouchPanPosition.x = ed.x;
  47312. previousMultiTouchPanPosition.y = ed.y;
  47313. }
  47314. }
  47315. previousPinchSquaredDistance = pinchSquaredDistance;
  47316. }
  47317. }
  47318. };
  47319. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47320. this._onContextMenu = function (evt) {
  47321. evt.preventDefault();
  47322. };
  47323. if (!this.camera._useCtrlForPanning) {
  47324. element.addEventListener("contextmenu", this._onContextMenu, false);
  47325. }
  47326. this._onLostFocus = function () {
  47327. //this._keys = [];
  47328. pointA = pointB = null;
  47329. previousPinchSquaredDistance = 0;
  47330. previousMultiTouchPanPosition.isPaning = false;
  47331. previousMultiTouchPanPosition.isPinching = false;
  47332. twoFingerActivityCount = 0;
  47333. cacheSoloPointer = null;
  47334. initialDistance = 0;
  47335. };
  47336. this._onMouseMove = function (evt) {
  47337. if (!engine.isPointerLock) {
  47338. return;
  47339. }
  47340. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47341. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47342. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47343. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47344. if (!noPreventDefault) {
  47345. evt.preventDefault();
  47346. }
  47347. };
  47348. this._onGestureStart = function (e) {
  47349. if (window.MSGesture === undefined) {
  47350. return;
  47351. }
  47352. if (!_this._MSGestureHandler) {
  47353. _this._MSGestureHandler = new MSGesture();
  47354. _this._MSGestureHandler.target = element;
  47355. }
  47356. _this._MSGestureHandler.addPointer(e.pointerId);
  47357. };
  47358. this._onGesture = function (e) {
  47359. _this.camera.radius *= e.scale;
  47360. if (e.preventDefault) {
  47361. if (!noPreventDefault) {
  47362. e.stopPropagation();
  47363. e.preventDefault();
  47364. }
  47365. }
  47366. };
  47367. element.addEventListener("mousemove", this._onMouseMove, false);
  47368. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47369. element.addEventListener("MSGestureChange", this._onGesture, false);
  47370. BABYLON.Tools.RegisterTopRootEvents([
  47371. { name: "blur", handler: this._onLostFocus }
  47372. ]);
  47373. };
  47374. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47375. if (this._onLostFocus) {
  47376. BABYLON.Tools.UnregisterTopRootEvents([
  47377. { name: "blur", handler: this._onLostFocus }
  47378. ]);
  47379. }
  47380. if (element && this._observer) {
  47381. this.camera.getScene().onPointerObservable.remove(this._observer);
  47382. this._observer = null;
  47383. if (this._onContextMenu) {
  47384. element.removeEventListener("contextmenu", this._onContextMenu);
  47385. }
  47386. if (this._onMouseMove) {
  47387. element.removeEventListener("mousemove", this._onMouseMove);
  47388. }
  47389. if (this._onGestureStart) {
  47390. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47391. }
  47392. if (this._onGesture) {
  47393. element.removeEventListener("MSGestureChange", this._onGesture);
  47394. }
  47395. this._isPanClick = false;
  47396. this.pinchInwards = true;
  47397. this._onMouseMove = null;
  47398. this._onGestureStart = null;
  47399. this._onGesture = null;
  47400. this._MSGestureHandler = null;
  47401. this._onLostFocus = null;
  47402. this._onContextMenu = null;
  47403. }
  47404. };
  47405. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47406. return "ArcRotateCameraPointersInput";
  47407. };
  47408. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47409. return "pointers";
  47410. };
  47411. __decorate([
  47412. BABYLON.serialize()
  47413. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47414. __decorate([
  47415. BABYLON.serialize()
  47416. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47417. __decorate([
  47418. BABYLON.serialize()
  47419. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47420. __decorate([
  47421. BABYLON.serialize()
  47422. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47423. __decorate([
  47424. BABYLON.serialize()
  47425. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47426. __decorate([
  47427. BABYLON.serialize()
  47428. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47429. __decorate([
  47430. BABYLON.serialize()
  47431. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47432. __decorate([
  47433. BABYLON.serialize()
  47434. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47435. return ArcRotateCameraPointersInput;
  47436. }());
  47437. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47438. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47439. })(BABYLON || (BABYLON = {}));
  47440. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47441. var BABYLON;
  47442. (function (BABYLON) {
  47443. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47444. __extends(ArcRotateCameraInputsManager, _super);
  47445. function ArcRotateCameraInputsManager(camera) {
  47446. return _super.call(this, camera) || this;
  47447. }
  47448. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47449. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47450. return this;
  47451. };
  47452. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47453. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47454. return this;
  47455. };
  47456. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47457. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47458. return this;
  47459. };
  47460. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47461. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47462. return this;
  47463. };
  47464. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47465. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47466. return this;
  47467. };
  47468. return ArcRotateCameraInputsManager;
  47469. }(BABYLON.CameraInputsManager));
  47470. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47471. })(BABYLON || (BABYLON = {}));
  47472. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47473. var BABYLON;
  47474. (function (BABYLON) {
  47475. var ArcRotateCamera = /** @class */ (function (_super) {
  47476. __extends(ArcRotateCamera, _super);
  47477. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47478. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47479. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47480. _this.inertialAlphaOffset = 0;
  47481. _this.inertialBetaOffset = 0;
  47482. _this.inertialRadiusOffset = 0;
  47483. _this.lowerAlphaLimit = null;
  47484. _this.upperAlphaLimit = null;
  47485. _this.lowerBetaLimit = 0.01;
  47486. _this.upperBetaLimit = Math.PI;
  47487. _this.lowerRadiusLimit = null;
  47488. _this.upperRadiusLimit = null;
  47489. _this.inertialPanningX = 0;
  47490. _this.inertialPanningY = 0;
  47491. _this.pinchToPanMaxDistance = 20;
  47492. _this.panningDistanceLimit = null;
  47493. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47494. _this.panningInertia = 0.9;
  47495. //-- end properties for backward compatibility for inputs
  47496. _this.zoomOnFactor = 1;
  47497. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47498. _this.allowUpsideDown = true;
  47499. _this._viewMatrix = new BABYLON.Matrix();
  47500. // Panning
  47501. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47502. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47503. _this.checkCollisions = false;
  47504. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47505. _this._previousPosition = BABYLON.Vector3.Zero();
  47506. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47507. _this._newPosition = BABYLON.Vector3.Zero();
  47508. _this._computationVector = BABYLON.Vector3.Zero();
  47509. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47510. if (collidedMesh === void 0) { collidedMesh = null; }
  47511. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47512. newPosition.multiplyInPlace(_this._collider._radius);
  47513. }
  47514. if (!collidedMesh) {
  47515. _this._previousPosition.copyFrom(_this.position);
  47516. }
  47517. else {
  47518. _this.setPosition(newPosition);
  47519. if (_this.onCollide) {
  47520. _this.onCollide(collidedMesh);
  47521. }
  47522. }
  47523. // Recompute because of constraints
  47524. var cosa = Math.cos(_this.alpha);
  47525. var sina = Math.sin(_this.alpha);
  47526. var cosb = Math.cos(_this.beta);
  47527. var sinb = Math.sin(_this.beta);
  47528. if (sinb === 0) {
  47529. sinb = 0.0001;
  47530. }
  47531. var target = _this._getTargetPosition();
  47532. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47533. target.addToRef(_this._computationVector, _this._newPosition);
  47534. _this.position.copyFrom(_this._newPosition);
  47535. var up = _this.upVector;
  47536. if (_this.allowUpsideDown && _this.beta < 0) {
  47537. up = up.clone();
  47538. up = up.negate();
  47539. }
  47540. _this._computeViewMatrix(_this.position, target, up);
  47541. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47542. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47543. _this._collisionTriggered = false;
  47544. };
  47545. _this._target = BABYLON.Vector3.Zero();
  47546. if (target) {
  47547. _this.setTarget(target);
  47548. }
  47549. _this.alpha = alpha;
  47550. _this.beta = beta;
  47551. _this.radius = radius;
  47552. _this.getViewMatrix();
  47553. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47554. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47555. return _this;
  47556. }
  47557. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47558. get: function () {
  47559. return this._target;
  47560. },
  47561. set: function (value) {
  47562. this.setTarget(value);
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47568. //-- begin properties for backward compatibility for inputs
  47569. get: function () {
  47570. var pointers = this.inputs.attached["pointers"];
  47571. if (pointers)
  47572. return pointers.angularSensibilityX;
  47573. return 0;
  47574. },
  47575. set: function (value) {
  47576. var pointers = this.inputs.attached["pointers"];
  47577. if (pointers) {
  47578. pointers.angularSensibilityX = value;
  47579. }
  47580. },
  47581. enumerable: true,
  47582. configurable: true
  47583. });
  47584. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47585. get: function () {
  47586. var pointers = this.inputs.attached["pointers"];
  47587. if (pointers)
  47588. return pointers.angularSensibilityY;
  47589. return 0;
  47590. },
  47591. set: function (value) {
  47592. var pointers = this.inputs.attached["pointers"];
  47593. if (pointers) {
  47594. pointers.angularSensibilityY = value;
  47595. }
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47601. get: function () {
  47602. var pointers = this.inputs.attached["pointers"];
  47603. if (pointers)
  47604. return pointers.pinchPrecision;
  47605. return 0;
  47606. },
  47607. set: function (value) {
  47608. var pointers = this.inputs.attached["pointers"];
  47609. if (pointers) {
  47610. pointers.pinchPrecision = value;
  47611. }
  47612. },
  47613. enumerable: true,
  47614. configurable: true
  47615. });
  47616. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47617. get: function () {
  47618. var pointers = this.inputs.attached["pointers"];
  47619. if (pointers)
  47620. return pointers.pinchDeltaPercentage;
  47621. return 0;
  47622. },
  47623. set: function (value) {
  47624. var pointers = this.inputs.attached["pointers"];
  47625. if (pointers) {
  47626. pointers.pinchDeltaPercentage = value;
  47627. }
  47628. },
  47629. enumerable: true,
  47630. configurable: true
  47631. });
  47632. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47633. get: function () {
  47634. var pointers = this.inputs.attached["pointers"];
  47635. if (pointers)
  47636. return pointers.panningSensibility;
  47637. return 0;
  47638. },
  47639. set: function (value) {
  47640. var pointers = this.inputs.attached["pointers"];
  47641. if (pointers) {
  47642. pointers.panningSensibility = value;
  47643. }
  47644. },
  47645. enumerable: true,
  47646. configurable: true
  47647. });
  47648. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47649. get: function () {
  47650. var keyboard = this.inputs.attached["keyboard"];
  47651. if (keyboard)
  47652. return keyboard.keysUp;
  47653. return [];
  47654. },
  47655. set: function (value) {
  47656. var keyboard = this.inputs.attached["keyboard"];
  47657. if (keyboard)
  47658. keyboard.keysUp = value;
  47659. },
  47660. enumerable: true,
  47661. configurable: true
  47662. });
  47663. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47664. get: function () {
  47665. var keyboard = this.inputs.attached["keyboard"];
  47666. if (keyboard)
  47667. return keyboard.keysDown;
  47668. return [];
  47669. },
  47670. set: function (value) {
  47671. var keyboard = this.inputs.attached["keyboard"];
  47672. if (keyboard)
  47673. keyboard.keysDown = value;
  47674. },
  47675. enumerable: true,
  47676. configurable: true
  47677. });
  47678. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47679. get: function () {
  47680. var keyboard = this.inputs.attached["keyboard"];
  47681. if (keyboard)
  47682. return keyboard.keysLeft;
  47683. return [];
  47684. },
  47685. set: function (value) {
  47686. var keyboard = this.inputs.attached["keyboard"];
  47687. if (keyboard)
  47688. keyboard.keysLeft = value;
  47689. },
  47690. enumerable: true,
  47691. configurable: true
  47692. });
  47693. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47694. get: function () {
  47695. var keyboard = this.inputs.attached["keyboard"];
  47696. if (keyboard)
  47697. return keyboard.keysRight;
  47698. return [];
  47699. },
  47700. set: function (value) {
  47701. var keyboard = this.inputs.attached["keyboard"];
  47702. if (keyboard)
  47703. keyboard.keysRight = value;
  47704. },
  47705. enumerable: true,
  47706. configurable: true
  47707. });
  47708. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47709. get: function () {
  47710. var mousewheel = this.inputs.attached["mousewheel"];
  47711. if (mousewheel)
  47712. return mousewheel.wheelPrecision;
  47713. return 0;
  47714. },
  47715. set: function (value) {
  47716. var mousewheel = this.inputs.attached["mousewheel"];
  47717. if (mousewheel)
  47718. mousewheel.wheelPrecision = value;
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47724. get: function () {
  47725. var mousewheel = this.inputs.attached["mousewheel"];
  47726. if (mousewheel)
  47727. return mousewheel.wheelDeltaPercentage;
  47728. return 0;
  47729. },
  47730. set: function (value) {
  47731. var mousewheel = this.inputs.attached["mousewheel"];
  47732. if (mousewheel)
  47733. mousewheel.wheelDeltaPercentage = value;
  47734. },
  47735. enumerable: true,
  47736. configurable: true
  47737. });
  47738. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47739. get: function () {
  47740. return this._bouncingBehavior;
  47741. },
  47742. enumerable: true,
  47743. configurable: true
  47744. });
  47745. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47746. get: function () {
  47747. return this._bouncingBehavior != null;
  47748. },
  47749. set: function (value) {
  47750. if (value === this.useBouncingBehavior) {
  47751. return;
  47752. }
  47753. if (value) {
  47754. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47755. this.addBehavior(this._bouncingBehavior);
  47756. }
  47757. else if (this._bouncingBehavior) {
  47758. this.removeBehavior(this._bouncingBehavior);
  47759. this._bouncingBehavior = null;
  47760. }
  47761. },
  47762. enumerable: true,
  47763. configurable: true
  47764. });
  47765. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47766. get: function () {
  47767. return this._framingBehavior;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47773. get: function () {
  47774. return this._framingBehavior != null;
  47775. },
  47776. set: function (value) {
  47777. if (value === this.useFramingBehavior) {
  47778. return;
  47779. }
  47780. if (value) {
  47781. this._framingBehavior = new BABYLON.FramingBehavior();
  47782. this.addBehavior(this._framingBehavior);
  47783. }
  47784. else if (this._framingBehavior) {
  47785. this.removeBehavior(this._framingBehavior);
  47786. this._framingBehavior = null;
  47787. }
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47793. get: function () {
  47794. return this._autoRotationBehavior;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47800. get: function () {
  47801. return this._autoRotationBehavior != null;
  47802. },
  47803. set: function (value) {
  47804. if (value === this.useAutoRotationBehavior) {
  47805. return;
  47806. }
  47807. if (value) {
  47808. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47809. this.addBehavior(this._autoRotationBehavior);
  47810. }
  47811. else if (this._autoRotationBehavior) {
  47812. this.removeBehavior(this._autoRotationBehavior);
  47813. this._autoRotationBehavior = null;
  47814. }
  47815. },
  47816. enumerable: true,
  47817. configurable: true
  47818. });
  47819. // Cache
  47820. ArcRotateCamera.prototype._initCache = function () {
  47821. _super.prototype._initCache.call(this);
  47822. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47823. this._cache.alpha = undefined;
  47824. this._cache.beta = undefined;
  47825. this._cache.radius = undefined;
  47826. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47827. };
  47828. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47829. if (!ignoreParentClass) {
  47830. _super.prototype._updateCache.call(this);
  47831. }
  47832. this._cache._target.copyFrom(this._getTargetPosition());
  47833. this._cache.alpha = this.alpha;
  47834. this._cache.beta = this.beta;
  47835. this._cache.radius = this.radius;
  47836. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47837. };
  47838. ArcRotateCamera.prototype._getTargetPosition = function () {
  47839. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47840. var pos = this._targetHost.getAbsolutePosition();
  47841. if (this._targetBoundingCenter) {
  47842. pos.addToRef(this._targetBoundingCenter, this._target);
  47843. }
  47844. else {
  47845. this._target.copyFrom(pos);
  47846. }
  47847. }
  47848. var lockedTargetPosition = this._getLockedTargetPosition();
  47849. if (lockedTargetPosition) {
  47850. return lockedTargetPosition;
  47851. }
  47852. return this._target;
  47853. };
  47854. ArcRotateCamera.prototype.storeState = function () {
  47855. this._storedAlpha = this.alpha;
  47856. this._storedBeta = this.beta;
  47857. this._storedRadius = this.radius;
  47858. this._storedTarget = this._getTargetPosition().clone();
  47859. return _super.prototype.storeState.call(this);
  47860. };
  47861. /**
  47862. * Restored camera state. You must call storeState() first
  47863. */
  47864. ArcRotateCamera.prototype._restoreStateValues = function () {
  47865. if (!_super.prototype._restoreStateValues.call(this)) {
  47866. return false;
  47867. }
  47868. this.alpha = this._storedAlpha;
  47869. this.beta = this._storedBeta;
  47870. this.radius = this._storedRadius;
  47871. this.setTarget(this._storedTarget.clone());
  47872. this.inertialAlphaOffset = 0;
  47873. this.inertialBetaOffset = 0;
  47874. this.inertialRadiusOffset = 0;
  47875. this.inertialPanningX = 0;
  47876. this.inertialPanningY = 0;
  47877. return true;
  47878. };
  47879. // Synchronized
  47880. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47881. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47882. return false;
  47883. return this._cache._target.equals(this._getTargetPosition())
  47884. && this._cache.alpha === this.alpha
  47885. && this._cache.beta === this.beta
  47886. && this._cache.radius === this.radius
  47887. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47888. };
  47889. // Methods
  47890. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47891. var _this = this;
  47892. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47893. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47894. this._useCtrlForPanning = useCtrlForPanning;
  47895. this._panningMouseButton = panningMouseButton;
  47896. this.inputs.attachElement(element, noPreventDefault);
  47897. this._reset = function () {
  47898. _this.inertialAlphaOffset = 0;
  47899. _this.inertialBetaOffset = 0;
  47900. _this.inertialRadiusOffset = 0;
  47901. _this.inertialPanningX = 0;
  47902. _this.inertialPanningY = 0;
  47903. };
  47904. };
  47905. ArcRotateCamera.prototype.detachControl = function (element) {
  47906. this.inputs.detachElement(element);
  47907. if (this._reset) {
  47908. this._reset();
  47909. }
  47910. };
  47911. ArcRotateCamera.prototype._checkInputs = function () {
  47912. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47913. if (this._collisionTriggered) {
  47914. return;
  47915. }
  47916. this.inputs.checkInputs();
  47917. // Inertia
  47918. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47919. var inertialAlphaOffset = this.inertialAlphaOffset;
  47920. if (this.beta <= 0)
  47921. inertialAlphaOffset *= -1;
  47922. if (this.getScene().useRightHandedSystem)
  47923. inertialAlphaOffset *= -1;
  47924. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47925. inertialAlphaOffset *= -1;
  47926. this.alpha += inertialAlphaOffset;
  47927. this.beta += this.inertialBetaOffset;
  47928. this.radius -= this.inertialRadiusOffset;
  47929. this.inertialAlphaOffset *= this.inertia;
  47930. this.inertialBetaOffset *= this.inertia;
  47931. this.inertialRadiusOffset *= this.inertia;
  47932. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47933. this.inertialAlphaOffset = 0;
  47934. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47935. this.inertialBetaOffset = 0;
  47936. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47937. this.inertialRadiusOffset = 0;
  47938. }
  47939. // Panning inertia
  47940. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47941. if (!this._localDirection) {
  47942. this._localDirection = BABYLON.Vector3.Zero();
  47943. this._transformedDirection = BABYLON.Vector3.Zero();
  47944. }
  47945. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47946. this._localDirection.multiplyInPlace(this.panningAxis);
  47947. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47948. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47949. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47950. if (!this.panningAxis.y) {
  47951. this._transformedDirection.y = 0;
  47952. }
  47953. if (!this._targetHost) {
  47954. if (this.panningDistanceLimit) {
  47955. this._transformedDirection.addInPlace(this._target);
  47956. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47957. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47958. this._target.copyFrom(this._transformedDirection);
  47959. }
  47960. }
  47961. else {
  47962. this._target.addInPlace(this._transformedDirection);
  47963. }
  47964. }
  47965. this.inertialPanningX *= this.panningInertia;
  47966. this.inertialPanningY *= this.panningInertia;
  47967. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47968. this.inertialPanningX = 0;
  47969. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47970. this.inertialPanningY = 0;
  47971. }
  47972. // Limits
  47973. this._checkLimits();
  47974. _super.prototype._checkInputs.call(this);
  47975. };
  47976. ArcRotateCamera.prototype._checkLimits = function () {
  47977. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47978. if (this.allowUpsideDown && this.beta > Math.PI) {
  47979. this.beta = this.beta - (2 * Math.PI);
  47980. }
  47981. }
  47982. else {
  47983. if (this.beta < this.lowerBetaLimit) {
  47984. this.beta = this.lowerBetaLimit;
  47985. }
  47986. }
  47987. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47988. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47989. this.beta = this.beta + (2 * Math.PI);
  47990. }
  47991. }
  47992. else {
  47993. if (this.beta > this.upperBetaLimit) {
  47994. this.beta = this.upperBetaLimit;
  47995. }
  47996. }
  47997. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47998. this.alpha = this.lowerAlphaLimit;
  47999. }
  48000. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48001. this.alpha = this.upperAlphaLimit;
  48002. }
  48003. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48004. this.radius = this.lowerRadiusLimit;
  48005. }
  48006. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48007. this.radius = this.upperRadiusLimit;
  48008. }
  48009. };
  48010. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48011. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48012. this.radius = this._computationVector.length();
  48013. if (this.radius === 0) {
  48014. this.radius = 0.0001; // Just to avoid division by zero
  48015. }
  48016. // Alpha
  48017. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48018. if (this._computationVector.z < 0) {
  48019. this.alpha = 2 * Math.PI - this.alpha;
  48020. }
  48021. // Beta
  48022. this.beta = Math.acos(this._computationVector.y / this.radius);
  48023. this._checkLimits();
  48024. };
  48025. ArcRotateCamera.prototype.setPosition = function (position) {
  48026. if (this.position.equals(position)) {
  48027. return;
  48028. }
  48029. this.position.copyFrom(position);
  48030. this.rebuildAnglesAndRadius();
  48031. };
  48032. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48033. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48034. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48035. if (target.getBoundingInfo) {
  48036. if (toBoundingCenter) {
  48037. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48038. }
  48039. else {
  48040. this._targetBoundingCenter = null;
  48041. }
  48042. this._targetHost = target;
  48043. this._target = this._getTargetPosition();
  48044. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48045. }
  48046. else {
  48047. var newTarget = target;
  48048. var currentTarget = this._getTargetPosition();
  48049. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48050. return;
  48051. }
  48052. this._targetHost = null;
  48053. this._target = newTarget;
  48054. this._targetBoundingCenter = null;
  48055. this.onMeshTargetChangedObservable.notifyObservers(null);
  48056. }
  48057. this.rebuildAnglesAndRadius();
  48058. };
  48059. ArcRotateCamera.prototype._getViewMatrix = function () {
  48060. // Compute
  48061. var cosa = Math.cos(this.alpha);
  48062. var sina = Math.sin(this.alpha);
  48063. var cosb = Math.cos(this.beta);
  48064. var sinb = Math.sin(this.beta);
  48065. if (sinb === 0) {
  48066. sinb = 0.0001;
  48067. }
  48068. var target = this._getTargetPosition();
  48069. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48070. target.addToRef(this._computationVector, this._newPosition);
  48071. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48072. if (!this._collider) {
  48073. this._collider = new BABYLON.Collider();
  48074. }
  48075. this._collider._radius = this.collisionRadius;
  48076. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48077. this._collisionTriggered = true;
  48078. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48079. }
  48080. else {
  48081. this.position.copyFrom(this._newPosition);
  48082. var up = this.upVector;
  48083. if (this.allowUpsideDown && sinb < 0) {
  48084. up = up.clone();
  48085. up = up.negate();
  48086. }
  48087. this._computeViewMatrix(this.position, target, up);
  48088. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48089. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48090. }
  48091. this._currentTarget = target;
  48092. return this._viewMatrix;
  48093. };
  48094. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48095. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48096. meshes = meshes || this.getScene().meshes;
  48097. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48098. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48099. this.radius = distance * this.zoomOnFactor;
  48100. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48101. };
  48102. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48103. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48104. var meshesOrMinMaxVector;
  48105. var distance;
  48106. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48107. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48108. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48109. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48110. }
  48111. else { //minMaxVector and distance
  48112. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48113. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48114. distance = minMaxVectorAndDistance.distance;
  48115. }
  48116. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48117. if (!doNotUpdateMaxZ) {
  48118. this.maxZ = distance * 2;
  48119. }
  48120. };
  48121. /**
  48122. * @override
  48123. * Override Camera.createRigCamera
  48124. */
  48125. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48126. var alphaShift = 0;
  48127. switch (this.cameraRigMode) {
  48128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48131. case BABYLON.Camera.RIG_MODE_VR:
  48132. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48133. break;
  48134. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48135. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48136. break;
  48137. }
  48138. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48139. rigCam._cameraRigParams = {};
  48140. return rigCam;
  48141. };
  48142. /**
  48143. * @override
  48144. * Override Camera._updateRigCameras
  48145. */
  48146. ArcRotateCamera.prototype._updateRigCameras = function () {
  48147. var camLeft = this._rigCameras[0];
  48148. var camRight = this._rigCameras[1];
  48149. camLeft.beta = camRight.beta = this.beta;
  48150. camLeft.radius = camRight.radius = this.radius;
  48151. switch (this.cameraRigMode) {
  48152. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48153. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48155. case BABYLON.Camera.RIG_MODE_VR:
  48156. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48157. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48158. break;
  48159. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48160. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48161. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48162. break;
  48163. }
  48164. _super.prototype._updateRigCameras.call(this);
  48165. };
  48166. ArcRotateCamera.prototype.dispose = function () {
  48167. this.inputs.clear();
  48168. _super.prototype.dispose.call(this);
  48169. };
  48170. ArcRotateCamera.prototype.getClassName = function () {
  48171. return "ArcRotateCamera";
  48172. };
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCamera.prototype, "alpha", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCamera.prototype, "beta", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCamera.prototype, "radius", void 0);
  48182. __decorate([
  48183. BABYLON.serializeAsVector3("target")
  48184. ], ArcRotateCamera.prototype, "_target", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48212. __decorate([
  48213. BABYLON.serialize()
  48214. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48215. __decorate([
  48216. BABYLON.serialize()
  48217. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48218. __decorate([
  48219. BABYLON.serialize()
  48220. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48221. __decorate([
  48222. BABYLON.serialize()
  48223. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48224. __decorate([
  48225. BABYLON.serializeAsVector3()
  48226. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48227. __decorate([
  48228. BABYLON.serialize()
  48229. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48230. __decorate([
  48231. BABYLON.serialize()
  48232. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48236. return ArcRotateCamera;
  48237. }(BABYLON.TargetCamera));
  48238. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48239. })(BABYLON || (BABYLON = {}));
  48240. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48241. var BABYLON;
  48242. (function (BABYLON) {
  48243. /**
  48244. * The HemisphericLight simulates the ambient environment light,
  48245. * so the passed direction is the light reflection direction, not the incoming direction.
  48246. */
  48247. var HemisphericLight = /** @class */ (function (_super) {
  48248. __extends(HemisphericLight, _super);
  48249. /**
  48250. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48251. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48252. * The HemisphericLight can't cast shadows.
  48253. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48254. * @param name The friendly name of the light
  48255. * @param direction The direction of the light reflection
  48256. * @param scene The scene the light belongs to
  48257. */
  48258. function HemisphericLight(name, direction, scene) {
  48259. var _this = _super.call(this, name, scene) || this;
  48260. /**
  48261. * The groundColor is the light in the opposite direction to the one specified during creation.
  48262. * 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.
  48263. */
  48264. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48265. _this.direction = direction || BABYLON.Vector3.Up();
  48266. return _this;
  48267. }
  48268. HemisphericLight.prototype._buildUniformLayout = function () {
  48269. this._uniformBuffer.addUniform("vLightData", 4);
  48270. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48271. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48272. this._uniformBuffer.addUniform("vLightGround", 3);
  48273. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48274. this._uniformBuffer.addUniform("depthValues", 2);
  48275. this._uniformBuffer.create();
  48276. };
  48277. /**
  48278. * Returns the string "HemisphericLight".
  48279. * @return The class name
  48280. */
  48281. HemisphericLight.prototype.getClassName = function () {
  48282. return "HemisphericLight";
  48283. };
  48284. /**
  48285. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48286. * Returns the updated direction.
  48287. * @param target The target the direction should point to
  48288. * @return The computed direction
  48289. */
  48290. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48291. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48292. return this.direction;
  48293. };
  48294. /**
  48295. * Returns the shadow generator associated to the light.
  48296. * @returns Always null for hemispheric lights because it does not support shadows.
  48297. */
  48298. HemisphericLight.prototype.getShadowGenerator = function () {
  48299. return null;
  48300. };
  48301. /**
  48302. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48303. * @param effect The effect to update
  48304. * @param lightIndex The index of the light in the effect to update
  48305. * @returns The hemispheric light
  48306. */
  48307. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48308. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48309. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48310. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48311. return this;
  48312. };
  48313. /**
  48314. * @hidden internal use only.
  48315. */
  48316. HemisphericLight.prototype._getWorldMatrix = function () {
  48317. if (!this._worldMatrix) {
  48318. this._worldMatrix = BABYLON.Matrix.Identity();
  48319. }
  48320. return this._worldMatrix;
  48321. };
  48322. /**
  48323. * Returns the integer 3.
  48324. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48325. */
  48326. HemisphericLight.prototype.getTypeID = function () {
  48327. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48328. };
  48329. __decorate([
  48330. BABYLON.serializeAsColor3()
  48331. ], HemisphericLight.prototype, "groundColor", void 0);
  48332. __decorate([
  48333. BABYLON.serializeAsVector3()
  48334. ], HemisphericLight.prototype, "direction", void 0);
  48335. return HemisphericLight;
  48336. }(BABYLON.Light));
  48337. BABYLON.HemisphericLight = HemisphericLight;
  48338. })(BABYLON || (BABYLON = {}));
  48339. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48340. var BABYLON;
  48341. (function (BABYLON) {
  48342. /**
  48343. * Base implementation IShadowLight
  48344. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48345. */
  48346. var ShadowLight = /** @class */ (function (_super) {
  48347. __extends(ShadowLight, _super);
  48348. function ShadowLight() {
  48349. var _this = _super !== null && _super.apply(this, arguments) || this;
  48350. _this._needProjectionMatrixCompute = true;
  48351. return _this;
  48352. }
  48353. ShadowLight.prototype._setPosition = function (value) {
  48354. this._position = value;
  48355. };
  48356. Object.defineProperty(ShadowLight.prototype, "position", {
  48357. /**
  48358. * Sets the position the shadow will be casted from. Also use as the light position for both
  48359. * point and spot lights.
  48360. */
  48361. get: function () {
  48362. return this._position;
  48363. },
  48364. /**
  48365. * Sets the position the shadow will be casted from. Also use as the light position for both
  48366. * point and spot lights.
  48367. */
  48368. set: function (value) {
  48369. this._setPosition(value);
  48370. },
  48371. enumerable: true,
  48372. configurable: true
  48373. });
  48374. ShadowLight.prototype._setDirection = function (value) {
  48375. this._direction = value;
  48376. };
  48377. Object.defineProperty(ShadowLight.prototype, "direction", {
  48378. /**
  48379. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48380. * Also use as the light direction on spot and directional lights.
  48381. */
  48382. get: function () {
  48383. return this._direction;
  48384. },
  48385. /**
  48386. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48387. * Also use as the light direction on spot and directional lights.
  48388. */
  48389. set: function (value) {
  48390. this._setDirection(value);
  48391. },
  48392. enumerable: true,
  48393. configurable: true
  48394. });
  48395. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48396. /**
  48397. * Gets the shadow projection clipping minimum z value.
  48398. */
  48399. get: function () {
  48400. return this._shadowMinZ;
  48401. },
  48402. /**
  48403. * Sets the shadow projection clipping minimum z value.
  48404. */
  48405. set: function (value) {
  48406. this._shadowMinZ = value;
  48407. this.forceProjectionMatrixCompute();
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48413. /**
  48414. * Sets the shadow projection clipping maximum z value.
  48415. */
  48416. get: function () {
  48417. return this._shadowMaxZ;
  48418. },
  48419. /**
  48420. * Gets the shadow projection clipping maximum z value.
  48421. */
  48422. set: function (value) {
  48423. this._shadowMaxZ = value;
  48424. this.forceProjectionMatrixCompute();
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. /**
  48430. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48431. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48432. */
  48433. ShadowLight.prototype.computeTransformedInformation = function () {
  48434. if (this.parent && this.parent.getWorldMatrix) {
  48435. if (!this.transformedPosition) {
  48436. this.transformedPosition = BABYLON.Vector3.Zero();
  48437. }
  48438. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48439. // In case the direction is present.
  48440. if (this.direction) {
  48441. if (!this.transformedDirection) {
  48442. this.transformedDirection = BABYLON.Vector3.Zero();
  48443. }
  48444. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48445. }
  48446. return true;
  48447. }
  48448. return false;
  48449. };
  48450. /**
  48451. * Return the depth scale used for the shadow map.
  48452. * @returns the depth scale.
  48453. */
  48454. ShadowLight.prototype.getDepthScale = function () {
  48455. return 50.0;
  48456. };
  48457. /**
  48458. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48459. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48460. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48461. */
  48462. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48463. return this.transformedDirection ? this.transformedDirection : this.direction;
  48464. };
  48465. /**
  48466. * Returns the ShadowLight absolute position in the World.
  48467. * @returns the position vector in world space
  48468. */
  48469. ShadowLight.prototype.getAbsolutePosition = function () {
  48470. return this.transformedPosition ? this.transformedPosition : this.position;
  48471. };
  48472. /**
  48473. * Sets the ShadowLight direction toward the passed target.
  48474. * @param target The point tot target in local space
  48475. * @returns the updated ShadowLight direction
  48476. */
  48477. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48478. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48479. return this.direction;
  48480. };
  48481. /**
  48482. * Returns the light rotation in euler definition.
  48483. * @returns the x y z rotation in local space.
  48484. */
  48485. ShadowLight.prototype.getRotation = function () {
  48486. this.direction.normalize();
  48487. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48488. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48489. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48490. };
  48491. /**
  48492. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48493. * @returns true if a cube texture needs to be use
  48494. */
  48495. ShadowLight.prototype.needCube = function () {
  48496. return false;
  48497. };
  48498. /**
  48499. * Detects if the projection matrix requires to be recomputed this frame.
  48500. * @returns true if it requires to be recomputed otherwise, false.
  48501. */
  48502. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48503. return this._needProjectionMatrixCompute;
  48504. };
  48505. /**
  48506. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48507. */
  48508. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48509. this._needProjectionMatrixCompute = true;
  48510. };
  48511. /**
  48512. * Get the world matrix of the sahdow lights.
  48513. * @hidden Internal Use Only
  48514. */
  48515. ShadowLight.prototype._getWorldMatrix = function () {
  48516. if (!this._worldMatrix) {
  48517. this._worldMatrix = BABYLON.Matrix.Identity();
  48518. }
  48519. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48520. return this._worldMatrix;
  48521. };
  48522. /**
  48523. * Gets the minZ used for shadow according to both the scene and the light.
  48524. * @param activeCamera The camera we are returning the min for
  48525. * @returns the depth min z
  48526. */
  48527. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48528. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48529. };
  48530. /**
  48531. * Gets the maxZ used for shadow according to both the scene and the light.
  48532. * @param activeCamera The camera we are returning the max for
  48533. * @returns the depth max z
  48534. */
  48535. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48536. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48537. };
  48538. /**
  48539. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48540. * @param matrix The materix to updated with the projection information
  48541. * @param viewMatrix The transform matrix of the light
  48542. * @param renderList The list of mesh to render in the map
  48543. * @returns The current light
  48544. */
  48545. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48546. if (this.customProjectionMatrixBuilder) {
  48547. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48548. }
  48549. else {
  48550. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48551. }
  48552. return this;
  48553. };
  48554. __decorate([
  48555. BABYLON.serializeAsVector3()
  48556. ], ShadowLight.prototype, "position", null);
  48557. __decorate([
  48558. BABYLON.serializeAsVector3()
  48559. ], ShadowLight.prototype, "direction", null);
  48560. __decorate([
  48561. BABYLON.serialize()
  48562. ], ShadowLight.prototype, "shadowMinZ", null);
  48563. __decorate([
  48564. BABYLON.serialize()
  48565. ], ShadowLight.prototype, "shadowMaxZ", null);
  48566. return ShadowLight;
  48567. }(BABYLON.Light));
  48568. BABYLON.ShadowLight = ShadowLight;
  48569. })(BABYLON || (BABYLON = {}));
  48570. //# sourceMappingURL=babylon.shadowLight.js.map
  48571. var BABYLON;
  48572. (function (BABYLON) {
  48573. /**
  48574. * A point light is a light defined by an unique point in world space.
  48575. * The light is emitted in every direction from this point.
  48576. * A good example of a point light is a standard light bulb.
  48577. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48578. */
  48579. var PointLight = /** @class */ (function (_super) {
  48580. __extends(PointLight, _super);
  48581. /**
  48582. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48583. * A PointLight emits the light in every direction.
  48584. * It can cast shadows.
  48585. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48586. * ```javascript
  48587. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48588. * ```
  48589. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48590. * @param name The light friendly name
  48591. * @param position The position of the point light in the scene
  48592. * @param scene The scene the lights belongs to
  48593. */
  48594. function PointLight(name, position, scene) {
  48595. var _this = _super.call(this, name, scene) || this;
  48596. _this._shadowAngle = Math.PI / 2;
  48597. _this.position = position;
  48598. return _this;
  48599. }
  48600. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48601. /**
  48602. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48603. * This specifies what angle the shadow will use to be created.
  48604. *
  48605. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48606. */
  48607. get: function () {
  48608. return this._shadowAngle;
  48609. },
  48610. /**
  48611. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48612. * This specifies what angle the shadow will use to be created.
  48613. *
  48614. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48615. */
  48616. set: function (value) {
  48617. this._shadowAngle = value;
  48618. this.forceProjectionMatrixCompute();
  48619. },
  48620. enumerable: true,
  48621. configurable: true
  48622. });
  48623. Object.defineProperty(PointLight.prototype, "direction", {
  48624. /**
  48625. * Gets the direction if it has been set.
  48626. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48627. */
  48628. get: function () {
  48629. return this._direction;
  48630. },
  48631. /**
  48632. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48633. */
  48634. set: function (value) {
  48635. var previousNeedCube = this.needCube();
  48636. this._direction = value;
  48637. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48638. this._shadowGenerator.recreateShadowMap();
  48639. }
  48640. },
  48641. enumerable: true,
  48642. configurable: true
  48643. });
  48644. /**
  48645. * Returns the string "PointLight"
  48646. * @returns the class name
  48647. */
  48648. PointLight.prototype.getClassName = function () {
  48649. return "PointLight";
  48650. };
  48651. /**
  48652. * Returns the integer 0.
  48653. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48654. */
  48655. PointLight.prototype.getTypeID = function () {
  48656. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48657. };
  48658. /**
  48659. * Specifies wether or not the shadowmap should be a cube texture.
  48660. * @returns true if the shadowmap needs to be a cube texture.
  48661. */
  48662. PointLight.prototype.needCube = function () {
  48663. return !this.direction;
  48664. };
  48665. /**
  48666. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48667. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48668. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48669. */
  48670. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48671. if (this.direction) {
  48672. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48673. }
  48674. else {
  48675. switch (faceIndex) {
  48676. case 0:
  48677. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48678. case 1:
  48679. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48680. case 2:
  48681. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48682. case 3:
  48683. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48684. case 4:
  48685. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48686. case 5:
  48687. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48688. }
  48689. }
  48690. return BABYLON.Vector3.Zero();
  48691. };
  48692. /**
  48693. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48694. * - fov = PI / 2
  48695. * - aspect ratio : 1.0
  48696. * - z-near and far equal to the active camera minZ and maxZ.
  48697. * Returns the PointLight.
  48698. */
  48699. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48700. var activeCamera = this.getScene().activeCamera;
  48701. if (!activeCamera) {
  48702. return;
  48703. }
  48704. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48705. };
  48706. PointLight.prototype._buildUniformLayout = function () {
  48707. this._uniformBuffer.addUniform("vLightData", 4);
  48708. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48709. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48710. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48711. this._uniformBuffer.addUniform("depthValues", 2);
  48712. this._uniformBuffer.create();
  48713. };
  48714. /**
  48715. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48716. * @param effect The effect to update
  48717. * @param lightIndex The index of the light in the effect to update
  48718. * @returns The point light
  48719. */
  48720. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48721. if (this.computeTransformedInformation()) {
  48722. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48723. return this;
  48724. }
  48725. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48726. return this;
  48727. };
  48728. __decorate([
  48729. BABYLON.serialize()
  48730. ], PointLight.prototype, "shadowAngle", null);
  48731. return PointLight;
  48732. }(BABYLON.ShadowLight));
  48733. BABYLON.PointLight = PointLight;
  48734. })(BABYLON || (BABYLON = {}));
  48735. //# sourceMappingURL=babylon.pointLight.js.map
  48736. var BABYLON;
  48737. (function (BABYLON) {
  48738. /**
  48739. * A directional light is defined by a direction (what a surprise!).
  48740. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48741. * 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.
  48742. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48743. */
  48744. var DirectionalLight = /** @class */ (function (_super) {
  48745. __extends(DirectionalLight, _super);
  48746. /**
  48747. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48748. * The directional light is emitted from everywhere in the given direction.
  48749. * It can cast shawdows.
  48750. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48751. * @param name The friendly name of the light
  48752. * @param direction The direction of the light
  48753. * @param scene The scene the light belongs to
  48754. */
  48755. function DirectionalLight(name, direction, scene) {
  48756. var _this = _super.call(this, name, scene) || this;
  48757. _this._shadowFrustumSize = 0;
  48758. _this._shadowOrthoScale = 0.1;
  48759. /**
  48760. * Automatically compute the projection matrix to best fit (including all the casters)
  48761. * on each frame.
  48762. */
  48763. _this.autoUpdateExtends = true;
  48764. // Cache
  48765. _this._orthoLeft = Number.MAX_VALUE;
  48766. _this._orthoRight = Number.MIN_VALUE;
  48767. _this._orthoTop = Number.MIN_VALUE;
  48768. _this._orthoBottom = Number.MAX_VALUE;
  48769. _this.position = direction.scale(-1.0);
  48770. _this.direction = direction;
  48771. return _this;
  48772. }
  48773. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48774. /**
  48775. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48776. */
  48777. get: function () {
  48778. return this._shadowFrustumSize;
  48779. },
  48780. /**
  48781. * Specifies a fix frustum size for the shadow generation.
  48782. */
  48783. set: function (value) {
  48784. this._shadowFrustumSize = value;
  48785. this.forceProjectionMatrixCompute();
  48786. },
  48787. enumerable: true,
  48788. configurable: true
  48789. });
  48790. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48791. /**
  48792. * Gets the shadow projection scale against the optimal computed one.
  48793. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48794. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48795. */
  48796. get: function () {
  48797. return this._shadowOrthoScale;
  48798. },
  48799. /**
  48800. * Sets the shadow projection scale against the optimal computed one.
  48801. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48802. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48803. */
  48804. set: function (value) {
  48805. this._shadowOrthoScale = value;
  48806. this.forceProjectionMatrixCompute();
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. /**
  48812. * Returns the string "DirectionalLight".
  48813. * @return The class name
  48814. */
  48815. DirectionalLight.prototype.getClassName = function () {
  48816. return "DirectionalLight";
  48817. };
  48818. /**
  48819. * Returns the integer 1.
  48820. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48821. */
  48822. DirectionalLight.prototype.getTypeID = function () {
  48823. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48824. };
  48825. /**
  48826. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48827. * Returns the DirectionalLight Shadow projection matrix.
  48828. */
  48829. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48830. if (this.shadowFrustumSize > 0) {
  48831. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48832. }
  48833. else {
  48834. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48835. }
  48836. };
  48837. /**
  48838. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48839. * Returns the DirectionalLight Shadow projection matrix.
  48840. */
  48841. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48842. var activeCamera = this.getScene().activeCamera;
  48843. if (!activeCamera) {
  48844. return;
  48845. }
  48846. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48847. };
  48848. /**
  48849. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48850. * Returns the DirectionalLight Shadow projection matrix.
  48851. */
  48852. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48853. var activeCamera = this.getScene().activeCamera;
  48854. if (!activeCamera) {
  48855. return;
  48856. }
  48857. // Check extends
  48858. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48859. var tempVector3 = BABYLON.Vector3.Zero();
  48860. this._orthoLeft = Number.MAX_VALUE;
  48861. this._orthoRight = Number.MIN_VALUE;
  48862. this._orthoTop = Number.MIN_VALUE;
  48863. this._orthoBottom = Number.MAX_VALUE;
  48864. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48865. var mesh = renderList[meshIndex];
  48866. if (!mesh) {
  48867. continue;
  48868. }
  48869. var boundingInfo = mesh.getBoundingInfo();
  48870. var boundingBox = boundingInfo.boundingBox;
  48871. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48872. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48873. if (tempVector3.x < this._orthoLeft)
  48874. this._orthoLeft = tempVector3.x;
  48875. if (tempVector3.y < this._orthoBottom)
  48876. this._orthoBottom = tempVector3.y;
  48877. if (tempVector3.x > this._orthoRight)
  48878. this._orthoRight = tempVector3.x;
  48879. if (tempVector3.y > this._orthoTop)
  48880. this._orthoTop = tempVector3.y;
  48881. }
  48882. }
  48883. }
  48884. var xOffset = this._orthoRight - this._orthoLeft;
  48885. var yOffset = this._orthoTop - this._orthoBottom;
  48886. 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);
  48887. };
  48888. DirectionalLight.prototype._buildUniformLayout = function () {
  48889. this._uniformBuffer.addUniform("vLightData", 4);
  48890. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48891. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48892. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48893. this._uniformBuffer.addUniform("depthValues", 2);
  48894. this._uniformBuffer.create();
  48895. };
  48896. /**
  48897. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48898. * @param effect The effect to update
  48899. * @param lightIndex The index of the light in the effect to update
  48900. * @returns The directional light
  48901. */
  48902. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48903. if (this.computeTransformedInformation()) {
  48904. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48905. return this;
  48906. }
  48907. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48908. return this;
  48909. };
  48910. /**
  48911. * Gets the minZ used for shadow according to both the scene and the light.
  48912. *
  48913. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48914. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48915. * @param activeCamera The camera we are returning the min for
  48916. * @returns the depth min z
  48917. */
  48918. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48919. return 1;
  48920. };
  48921. /**
  48922. * Gets the maxZ used for shadow according to both the scene and the light.
  48923. *
  48924. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48925. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48926. * @param activeCamera The camera we are returning the max for
  48927. * @returns the depth max z
  48928. */
  48929. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48930. return 1;
  48931. };
  48932. __decorate([
  48933. BABYLON.serialize()
  48934. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48935. __decorate([
  48936. BABYLON.serialize()
  48937. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48938. __decorate([
  48939. BABYLON.serialize()
  48940. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48941. return DirectionalLight;
  48942. }(BABYLON.ShadowLight));
  48943. BABYLON.DirectionalLight = DirectionalLight;
  48944. })(BABYLON || (BABYLON = {}));
  48945. //# sourceMappingURL=babylon.directionalLight.js.map
  48946. var BABYLON;
  48947. (function (BABYLON) {
  48948. /**
  48949. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48950. * These values define a cone of light starting from the position, emitting toward the direction.
  48951. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48952. * and the exponent defines the speed of the decay of the light with distance (reach).
  48953. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48954. */
  48955. var SpotLight = /** @class */ (function (_super) {
  48956. __extends(SpotLight, _super);
  48957. /**
  48958. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48959. * It can cast shadows.
  48960. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48961. * @param name The light friendly name
  48962. * @param position The position of the spot light in the scene
  48963. * @param direction The direction of the light in the scene
  48964. * @param angle The cone angle of the light in Radians
  48965. * @param exponent The light decay speed with the distance from the emission spot
  48966. * @param scene The scene the lights belongs to
  48967. */
  48968. function SpotLight(name, position, direction, angle, exponent, scene) {
  48969. var _this = _super.call(this, name, scene) || this;
  48970. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48971. _this._projectionTextureLightNear = 1e-6;
  48972. _this._projectionTextureLightFar = 1000.0;
  48973. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48974. _this._projectionTextureViewLightDirty = true;
  48975. _this._projectionTextureProjectionLightDirty = true;
  48976. _this._projectionTextureDirty = true;
  48977. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48978. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48979. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48980. _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);
  48981. _this.position = position;
  48982. _this.direction = direction;
  48983. _this.angle = angle;
  48984. _this.exponent = exponent;
  48985. return _this;
  48986. }
  48987. Object.defineProperty(SpotLight.prototype, "angle", {
  48988. /**
  48989. * Gets the cone angle of the spot light in Radians.
  48990. */
  48991. get: function () {
  48992. return this._angle;
  48993. },
  48994. /**
  48995. * Sets the cone angle of the spot light in Radians.
  48996. */
  48997. set: function (value) {
  48998. this._angle = value;
  48999. this._projectionTextureProjectionLightDirty = true;
  49000. this.forceProjectionMatrixCompute();
  49001. },
  49002. enumerable: true,
  49003. configurable: true
  49004. });
  49005. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49006. /**
  49007. * Allows scaling the angle of the light for shadow generation only.
  49008. */
  49009. get: function () {
  49010. return this._shadowAngleScale;
  49011. },
  49012. /**
  49013. * Allows scaling the angle of the light for shadow generation only.
  49014. */
  49015. set: function (value) {
  49016. this._shadowAngleScale = value;
  49017. this.forceProjectionMatrixCompute();
  49018. },
  49019. enumerable: true,
  49020. configurable: true
  49021. });
  49022. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49023. /**
  49024. * Allows reading the projecton texture
  49025. */
  49026. get: function () {
  49027. return this._projectionTextureMatrix;
  49028. },
  49029. enumerable: true,
  49030. configurable: true
  49031. });
  49032. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49033. /**
  49034. * Gets the near clip of the Spotlight for texture projection.
  49035. */
  49036. get: function () {
  49037. return this._projectionTextureLightNear;
  49038. },
  49039. /**
  49040. * Sets the near clip of the Spotlight for texture projection.
  49041. */
  49042. set: function (value) {
  49043. this._projectionTextureLightNear = value;
  49044. this._projectionTextureProjectionLightDirty = true;
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49050. /**
  49051. * Gets the far clip of the Spotlight for texture projection.
  49052. */
  49053. get: function () {
  49054. return this._projectionTextureLightFar;
  49055. },
  49056. /**
  49057. * Sets the far clip of the Spotlight for texture projection.
  49058. */
  49059. set: function (value) {
  49060. this._projectionTextureLightFar = value;
  49061. this._projectionTextureProjectionLightDirty = true;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49067. /**
  49068. * Gets the Up vector of the Spotlight for texture projection.
  49069. */
  49070. get: function () {
  49071. return this._projectionTextureUpDirection;
  49072. },
  49073. /**
  49074. * Sets the Up vector of the Spotlight for texture projection.
  49075. */
  49076. set: function (value) {
  49077. this._projectionTextureUpDirection = value;
  49078. this._projectionTextureProjectionLightDirty = true;
  49079. },
  49080. enumerable: true,
  49081. configurable: true
  49082. });
  49083. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49084. /**
  49085. * Gets the projection texture of the light.
  49086. */
  49087. get: function () {
  49088. return this._projectionTexture;
  49089. },
  49090. /**
  49091. * Sets the projection texture of the light.
  49092. */
  49093. set: function (value) {
  49094. this._projectionTexture = value;
  49095. this._projectionTextureDirty = true;
  49096. },
  49097. enumerable: true,
  49098. configurable: true
  49099. });
  49100. /**
  49101. * Returns the string "SpotLight".
  49102. * @returns the class name
  49103. */
  49104. SpotLight.prototype.getClassName = function () {
  49105. return "SpotLight";
  49106. };
  49107. /**
  49108. * Returns the integer 2.
  49109. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49110. */
  49111. SpotLight.prototype.getTypeID = function () {
  49112. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49113. };
  49114. /**
  49115. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49116. */
  49117. SpotLight.prototype._setDirection = function (value) {
  49118. _super.prototype._setDirection.call(this, value);
  49119. this._projectionTextureViewLightDirty = true;
  49120. };
  49121. /**
  49122. * Overrides the position setter to recompute the projection texture view light Matrix.
  49123. */
  49124. SpotLight.prototype._setPosition = function (value) {
  49125. _super.prototype._setPosition.call(this, value);
  49126. this._projectionTextureViewLightDirty = true;
  49127. };
  49128. /**
  49129. * 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.
  49130. * Returns the SpotLight.
  49131. */
  49132. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49133. var activeCamera = this.getScene().activeCamera;
  49134. if (!activeCamera) {
  49135. return;
  49136. }
  49137. this._shadowAngleScale = this._shadowAngleScale || 1;
  49138. var angle = this._shadowAngleScale * this._angle;
  49139. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49140. };
  49141. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49142. this._projectionTextureViewLightDirty = false;
  49143. this._projectionTextureDirty = true;
  49144. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49145. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49146. };
  49147. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49148. this._projectionTextureProjectionLightDirty = false;
  49149. this._projectionTextureDirty = true;
  49150. var light_far = this.projectionTextureLightFar;
  49151. var light_near = this.projectionTextureLightNear;
  49152. var P = light_far / (light_far - light_near);
  49153. var Q = -P * light_near;
  49154. var S = 1.0 / Math.tan(this._angle / 2.0);
  49155. var A = 1.0;
  49156. 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);
  49157. };
  49158. /**
  49159. * Main function for light texture projection matrix computing.
  49160. */
  49161. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49162. this._projectionTextureDirty = false;
  49163. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49164. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49165. };
  49166. SpotLight.prototype._buildUniformLayout = function () {
  49167. this._uniformBuffer.addUniform("vLightData", 4);
  49168. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49169. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49170. this._uniformBuffer.addUniform("vLightDirection", 3);
  49171. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49172. this._uniformBuffer.addUniform("depthValues", 2);
  49173. this._uniformBuffer.create();
  49174. };
  49175. /**
  49176. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49177. * @param effect The effect to update
  49178. * @param lightIndex The index of the light in the effect to update
  49179. * @returns The spot light
  49180. */
  49181. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49182. var normalizeDirection;
  49183. if (this.computeTransformedInformation()) {
  49184. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49185. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49186. }
  49187. else {
  49188. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49189. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49190. }
  49191. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49192. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49193. if (this._projectionTextureViewLightDirty) {
  49194. this._computeProjectionTextureViewLightMatrix();
  49195. }
  49196. if (this._projectionTextureProjectionLightDirty) {
  49197. this._computeProjectionTextureProjectionLightMatrix();
  49198. }
  49199. if (this._projectionTextureDirty) {
  49200. this._computeProjectionTextureMatrix();
  49201. }
  49202. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49203. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49204. }
  49205. return this;
  49206. };
  49207. /**
  49208. * Disposes the light and the associated resources.
  49209. */
  49210. SpotLight.prototype.dispose = function () {
  49211. _super.prototype.dispose.call(this);
  49212. if (this._projectionTexture) {
  49213. this._projectionTexture.dispose();
  49214. }
  49215. };
  49216. __decorate([
  49217. BABYLON.serialize()
  49218. ], SpotLight.prototype, "angle", null);
  49219. __decorate([
  49220. BABYLON.serialize()
  49221. ], SpotLight.prototype, "shadowAngleScale", null);
  49222. __decorate([
  49223. BABYLON.serialize()
  49224. ], SpotLight.prototype, "exponent", void 0);
  49225. __decorate([
  49226. BABYLON.serialize()
  49227. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49228. __decorate([
  49229. BABYLON.serialize()
  49230. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49231. __decorate([
  49232. BABYLON.serialize()
  49233. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49234. __decorate([
  49235. BABYLON.serializeAsTexture("projectedLightTexture")
  49236. ], SpotLight.prototype, "_projectionTexture", void 0);
  49237. return SpotLight;
  49238. }(BABYLON.ShadowLight));
  49239. BABYLON.SpotLight = SpotLight;
  49240. })(BABYLON || (BABYLON = {}));
  49241. //# sourceMappingURL=babylon.spotLight.js.map
  49242. var BABYLON;
  49243. (function (BABYLON) {
  49244. /**
  49245. * Class used to override all child animations of a given target
  49246. */
  49247. var AnimationPropertiesOverride = /** @class */ (function () {
  49248. function AnimationPropertiesOverride() {
  49249. /**
  49250. * Gets or sets a value indicating if animation blending must be used
  49251. */
  49252. this.enableBlending = false;
  49253. /**
  49254. * Gets or sets the blending speed to use when enableBlending is true
  49255. */
  49256. this.blendingSpeed = 0.01;
  49257. /**
  49258. * Gets or sets the default loop mode to use
  49259. */
  49260. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49261. }
  49262. return AnimationPropertiesOverride;
  49263. }());
  49264. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49265. })(BABYLON || (BABYLON = {}));
  49266. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49267. var BABYLON;
  49268. (function (BABYLON) {
  49269. /**
  49270. * Represents the range of an animation
  49271. */
  49272. var AnimationRange = /** @class */ (function () {
  49273. /**
  49274. * Initializes the range of an animation
  49275. * @param name The name of the animation range
  49276. * @param from The starting frame of the animation
  49277. * @param to The ending frame of the animation
  49278. */
  49279. function AnimationRange(
  49280. /**The name of the animation range**/
  49281. name,
  49282. /**The starting frame of the animation */
  49283. from,
  49284. /**The ending frame of the animation*/
  49285. to) {
  49286. this.name = name;
  49287. this.from = from;
  49288. this.to = to;
  49289. }
  49290. /**
  49291. * Makes a copy of the animation range
  49292. * @returns A copy of the animation range
  49293. */
  49294. AnimationRange.prototype.clone = function () {
  49295. return new AnimationRange(this.name, this.from, this.to);
  49296. };
  49297. return AnimationRange;
  49298. }());
  49299. BABYLON.AnimationRange = AnimationRange;
  49300. /**
  49301. * Composed of a frame, and an action function
  49302. */
  49303. var AnimationEvent = /** @class */ (function () {
  49304. /**
  49305. * Initializes the animation event
  49306. * @param frame The frame for which the event is triggered
  49307. * @param action The event to perform when triggered
  49308. * @param onlyOnce Specifies if the event should be triggered only once
  49309. */
  49310. function AnimationEvent(
  49311. /** The frame for which the event is triggered **/
  49312. frame,
  49313. /** The event to perform when triggered **/
  49314. action,
  49315. /** Specifies if the event should be triggered only once**/
  49316. onlyOnce) {
  49317. this.frame = frame;
  49318. this.action = action;
  49319. this.onlyOnce = onlyOnce;
  49320. /**
  49321. * Specifies if the animation event is done
  49322. */
  49323. this.isDone = false;
  49324. }
  49325. /** @hidden */
  49326. AnimationEvent.prototype._clone = function () {
  49327. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49328. };
  49329. return AnimationEvent;
  49330. }());
  49331. BABYLON.AnimationEvent = AnimationEvent;
  49332. /**
  49333. * A cursor which tracks a point on a path
  49334. */
  49335. var PathCursor = /** @class */ (function () {
  49336. /**
  49337. * Initializes the path cursor
  49338. * @param path The path to track
  49339. */
  49340. function PathCursor(path) {
  49341. this.path = path;
  49342. /**
  49343. * Stores path cursor callbacks for when an onchange event is triggered
  49344. */
  49345. this._onchange = new Array();
  49346. /**
  49347. * The value of the path cursor
  49348. */
  49349. this.value = 0;
  49350. /**
  49351. * The animation array of the path cursor
  49352. */
  49353. this.animations = new Array();
  49354. }
  49355. /**
  49356. * Gets the cursor point on the path
  49357. * @returns A point on the path cursor at the cursor location
  49358. */
  49359. PathCursor.prototype.getPoint = function () {
  49360. var point = this.path.getPointAtLengthPosition(this.value);
  49361. return new BABYLON.Vector3(point.x, 0, point.y);
  49362. };
  49363. /**
  49364. * Moves the cursor ahead by the step amount
  49365. * @param step The amount to move the cursor forward
  49366. * @returns This path cursor
  49367. */
  49368. PathCursor.prototype.moveAhead = function (step) {
  49369. if (step === void 0) { step = 0.002; }
  49370. this.move(step);
  49371. return this;
  49372. };
  49373. /**
  49374. * Moves the cursor behind by the step amount
  49375. * @param step The amount to move the cursor back
  49376. * @returns This path cursor
  49377. */
  49378. PathCursor.prototype.moveBack = function (step) {
  49379. if (step === void 0) { step = 0.002; }
  49380. this.move(-step);
  49381. return this;
  49382. };
  49383. /**
  49384. * Moves the cursor by the step amount
  49385. * If the step amount is greater than one, an exception is thrown
  49386. * @param step The amount to move the cursor
  49387. * @returns This path cursor
  49388. */
  49389. PathCursor.prototype.move = function (step) {
  49390. if (Math.abs(step) > 1) {
  49391. throw "step size should be less than 1.";
  49392. }
  49393. this.value += step;
  49394. this.ensureLimits();
  49395. this.raiseOnChange();
  49396. return this;
  49397. };
  49398. /**
  49399. * Ensures that the value is limited between zero and one
  49400. * @returns This path cursor
  49401. */
  49402. PathCursor.prototype.ensureLimits = function () {
  49403. while (this.value > 1) {
  49404. this.value -= 1;
  49405. }
  49406. while (this.value < 0) {
  49407. this.value += 1;
  49408. }
  49409. return this;
  49410. };
  49411. /**
  49412. * Runs onchange callbacks on change (used by the animation engine)
  49413. * @returns This path cursor
  49414. */
  49415. PathCursor.prototype.raiseOnChange = function () {
  49416. var _this = this;
  49417. this._onchange.forEach(function (f) { return f(_this); });
  49418. return this;
  49419. };
  49420. /**
  49421. * Executes a function on change
  49422. * @param f A path cursor onchange callback
  49423. * @returns This path cursor
  49424. */
  49425. PathCursor.prototype.onchange = function (f) {
  49426. this._onchange.push(f);
  49427. return this;
  49428. };
  49429. return PathCursor;
  49430. }());
  49431. BABYLON.PathCursor = PathCursor;
  49432. /**
  49433. * Enum for the animation key frame interpolation type
  49434. */
  49435. var AnimationKeyInterpolation;
  49436. (function (AnimationKeyInterpolation) {
  49437. /**
  49438. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49439. */
  49440. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49441. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49442. /**
  49443. * Class used to store any kind of animation
  49444. */
  49445. var Animation = /** @class */ (function () {
  49446. /**
  49447. * Initializes the animation
  49448. * @param name Name of the animation
  49449. * @param targetProperty Property to animate
  49450. * @param framePerSecond The frames per second of the animation
  49451. * @param dataType The data type of the animation
  49452. * @param loopMode The loop mode of the animation
  49453. * @param enableBlendings Specifies if blending should be enabled
  49454. */
  49455. function Animation(
  49456. /**Name of the animation */
  49457. name,
  49458. /**Property to animate */
  49459. targetProperty,
  49460. /**The frames per second of the animation */
  49461. framePerSecond,
  49462. /**The data type of the animation */
  49463. dataType,
  49464. /**The loop mode of the animation */
  49465. loopMode,
  49466. /**Specifies if blending should be enabled */
  49467. enableBlending) {
  49468. this.name = name;
  49469. this.targetProperty = targetProperty;
  49470. this.framePerSecond = framePerSecond;
  49471. this.dataType = dataType;
  49472. this.loopMode = loopMode;
  49473. this.enableBlending = enableBlending;
  49474. /**
  49475. * @hidden Internal use only
  49476. */
  49477. this._runtimeAnimations = new Array();
  49478. /**
  49479. * The set of event that will be linked to this animation
  49480. */
  49481. this._events = new Array();
  49482. /**
  49483. * Stores the blending speed of the animation
  49484. */
  49485. this.blendingSpeed = 0.01;
  49486. /**
  49487. * Stores the animation ranges for the animation
  49488. */
  49489. this._ranges = {};
  49490. this.targetPropertyPath = targetProperty.split(".");
  49491. this.dataType = dataType;
  49492. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49493. }
  49494. /**
  49495. * @hidden Internal use
  49496. */
  49497. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49498. var dataType = undefined;
  49499. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49500. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49501. }
  49502. else if (from instanceof BABYLON.Quaternion) {
  49503. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49504. }
  49505. else if (from instanceof BABYLON.Vector3) {
  49506. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49507. }
  49508. else if (from instanceof BABYLON.Vector2) {
  49509. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49510. }
  49511. else if (from instanceof BABYLON.Color3) {
  49512. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49513. }
  49514. else if (from instanceof BABYLON.Size) {
  49515. dataType = Animation.ANIMATIONTYPE_SIZE;
  49516. }
  49517. if (dataType == undefined) {
  49518. return null;
  49519. }
  49520. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49521. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49522. animation.setKeys(keys);
  49523. if (easingFunction !== undefined) {
  49524. animation.setEasingFunction(easingFunction);
  49525. }
  49526. return animation;
  49527. };
  49528. /**
  49529. * Sets up an animation
  49530. * @param property The property to animate
  49531. * @param animationType The animation type to apply
  49532. * @param framePerSecond The frames per second of the animation
  49533. * @param easingFunction The easing function used in the animation
  49534. * @returns The created animation
  49535. */
  49536. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49537. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49538. animation.setEasingFunction(easingFunction);
  49539. return animation;
  49540. };
  49541. /**
  49542. * Create and start an animation on a node
  49543. * @param name defines the name of the global animation that will be run on all nodes
  49544. * @param node defines the root node where the animation will take place
  49545. * @param targetProperty defines property to animate
  49546. * @param framePerSecond defines the number of frame per second yo use
  49547. * @param totalFrame defines the number of frames in total
  49548. * @param from defines the initial value
  49549. * @param to defines the final value
  49550. * @param loopMode defines which loop mode you want to use (off by default)
  49551. * @param easingFunction defines the easing function to use (linear by default)
  49552. * @param onAnimationEnd defines the callback to call when animation end
  49553. * @returns the animatable created for this animation
  49554. */
  49555. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49556. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49557. if (!animation) {
  49558. return null;
  49559. }
  49560. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49561. };
  49562. /**
  49563. * Create and start an animation on a node and its descendants
  49564. * @param name defines the name of the global animation that will be run on all nodes
  49565. * @param node defines the root node where the animation will take place
  49566. * @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
  49567. * @param targetProperty defines property to animate
  49568. * @param framePerSecond defines the number of frame per second to use
  49569. * @param totalFrame defines the number of frames in total
  49570. * @param from defines the initial value
  49571. * @param to defines the final value
  49572. * @param loopMode defines which loop mode you want to use (off by default)
  49573. * @param easingFunction defines the easing function to use (linear by default)
  49574. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49575. * @returns the list of animatables created for all nodes
  49576. * @example https://www.babylonjs-playground.com/#MH0VLI
  49577. */
  49578. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49579. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49580. if (!animation) {
  49581. return null;
  49582. }
  49583. var scene = node.getScene();
  49584. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49585. };
  49586. /**
  49587. * Creates a new animation, merges it with the existing animations and starts it
  49588. * @param name Name of the animation
  49589. * @param node Node which contains the scene that begins the animations
  49590. * @param targetProperty Specifies which property to animate
  49591. * @param framePerSecond The frames per second of the animation
  49592. * @param totalFrame The total number of frames
  49593. * @param from The frame at the beginning of the animation
  49594. * @param to The frame at the end of the animation
  49595. * @param loopMode Specifies the loop mode of the animation
  49596. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49597. * @param onAnimationEnd Callback to run once the animation is complete
  49598. * @returns Nullable animation
  49599. */
  49600. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49601. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49602. if (!animation) {
  49603. return null;
  49604. }
  49605. node.animations.push(animation);
  49606. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49607. };
  49608. /**
  49609. * Transition property of an host to the target Value
  49610. * @param property The property to transition
  49611. * @param targetValue The target Value of the property
  49612. * @param host The object where the property to animate belongs
  49613. * @param scene Scene used to run the animation
  49614. * @param frameRate Framerate (in frame/s) to use
  49615. * @param transition The transition type we want to use
  49616. * @param duration The duration of the animation, in milliseconds
  49617. * @param onAnimationEnd Callback trigger at the end of the animation
  49618. * @returns Nullable animation
  49619. */
  49620. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49621. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49622. if (duration <= 0) {
  49623. host[property] = targetValue;
  49624. if (onAnimationEnd) {
  49625. onAnimationEnd();
  49626. }
  49627. return null;
  49628. }
  49629. var endFrame = frameRate * (duration / 1000);
  49630. transition.setKeys([{
  49631. frame: 0,
  49632. value: host[property].clone ? host[property].clone() : host[property]
  49633. },
  49634. {
  49635. frame: endFrame,
  49636. value: targetValue
  49637. }]);
  49638. if (!host.animations) {
  49639. host.animations = [];
  49640. }
  49641. host.animations.push(transition);
  49642. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49643. animation.onAnimationEnd = onAnimationEnd;
  49644. return animation;
  49645. };
  49646. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49647. /**
  49648. * Return the array of runtime animations currently using this animation
  49649. */
  49650. get: function () {
  49651. return this._runtimeAnimations;
  49652. },
  49653. enumerable: true,
  49654. configurable: true
  49655. });
  49656. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49657. /**
  49658. * Specifies if any of the runtime animations are currently running
  49659. */
  49660. get: function () {
  49661. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49662. var runtimeAnimation = _a[_i];
  49663. if (!runtimeAnimation.isStopped) {
  49664. return true;
  49665. }
  49666. }
  49667. return false;
  49668. },
  49669. enumerable: true,
  49670. configurable: true
  49671. });
  49672. // Methods
  49673. /**
  49674. * Converts the animation to a string
  49675. * @param fullDetails support for multiple levels of logging within scene loading
  49676. * @returns String form of the animation
  49677. */
  49678. Animation.prototype.toString = function (fullDetails) {
  49679. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49680. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49681. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49682. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49683. if (fullDetails) {
  49684. ret += ", Ranges: {";
  49685. var first = true;
  49686. for (var name in this._ranges) {
  49687. if (first) {
  49688. ret += ", ";
  49689. first = false;
  49690. }
  49691. ret += name;
  49692. }
  49693. ret += "}";
  49694. }
  49695. return ret;
  49696. };
  49697. /**
  49698. * Add an event to this animation
  49699. * @param event Event to add
  49700. */
  49701. Animation.prototype.addEvent = function (event) {
  49702. this._events.push(event);
  49703. };
  49704. /**
  49705. * Remove all events found at the given frame
  49706. * @param frame The frame to remove events from
  49707. */
  49708. Animation.prototype.removeEvents = function (frame) {
  49709. for (var index = 0; index < this._events.length; index++) {
  49710. if (this._events[index].frame === frame) {
  49711. this._events.splice(index, 1);
  49712. index--;
  49713. }
  49714. }
  49715. };
  49716. /**
  49717. * Retrieves all the events from the animation
  49718. * @returns Events from the animation
  49719. */
  49720. Animation.prototype.getEvents = function () {
  49721. return this._events;
  49722. };
  49723. /**
  49724. * Creates an animation range
  49725. * @param name Name of the animation range
  49726. * @param from Starting frame of the animation range
  49727. * @param to Ending frame of the animation
  49728. */
  49729. Animation.prototype.createRange = function (name, from, to) {
  49730. // check name not already in use; could happen for bones after serialized
  49731. if (!this._ranges[name]) {
  49732. this._ranges[name] = new AnimationRange(name, from, to);
  49733. }
  49734. };
  49735. /**
  49736. * Deletes an animation range by name
  49737. * @param name Name of the animation range to delete
  49738. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49739. */
  49740. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49741. if (deleteFrames === void 0) { deleteFrames = true; }
  49742. var range = this._ranges[name];
  49743. if (!range) {
  49744. return;
  49745. }
  49746. if (deleteFrames) {
  49747. var from = range.from;
  49748. var to = range.to;
  49749. // this loop MUST go high to low for multiple splices to work
  49750. for (var key = this._keys.length - 1; key >= 0; key--) {
  49751. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49752. this._keys.splice(key, 1);
  49753. }
  49754. }
  49755. }
  49756. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49757. };
  49758. /**
  49759. * Gets the animation range by name, or null if not defined
  49760. * @param name Name of the animation range
  49761. * @returns Nullable animation range
  49762. */
  49763. Animation.prototype.getRange = function (name) {
  49764. return this._ranges[name];
  49765. };
  49766. /**
  49767. * Gets the key frames from the animation
  49768. * @returns The key frames of the animation
  49769. */
  49770. Animation.prototype.getKeys = function () {
  49771. return this._keys;
  49772. };
  49773. /**
  49774. * Gets the highest frame rate of the animation
  49775. * @returns Highest frame rate of the animation
  49776. */
  49777. Animation.prototype.getHighestFrame = function () {
  49778. var ret = 0;
  49779. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49780. if (ret < this._keys[key].frame) {
  49781. ret = this._keys[key].frame;
  49782. }
  49783. }
  49784. return ret;
  49785. };
  49786. /**
  49787. * Gets the easing function of the animation
  49788. * @returns Easing function of the animation
  49789. */
  49790. Animation.prototype.getEasingFunction = function () {
  49791. return this._easingFunction;
  49792. };
  49793. /**
  49794. * Sets the easing function of the animation
  49795. * @param easingFunction A custom mathematical formula for animation
  49796. */
  49797. Animation.prototype.setEasingFunction = function (easingFunction) {
  49798. this._easingFunction = easingFunction;
  49799. };
  49800. /**
  49801. * Interpolates a scalar linearly
  49802. * @param startValue Start value of the animation curve
  49803. * @param endValue End value of the animation curve
  49804. * @param gradient Scalar amount to interpolate
  49805. * @returns Interpolated scalar value
  49806. */
  49807. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49808. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49809. };
  49810. /**
  49811. * Interpolates a scalar cubically
  49812. * @param startValue Start value of the animation curve
  49813. * @param outTangent End tangent of the animation
  49814. * @param endValue End value of the animation curve
  49815. * @param inTangent Start tangent of the animation curve
  49816. * @param gradient Scalar amount to interpolate
  49817. * @returns Interpolated scalar value
  49818. */
  49819. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49820. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49821. };
  49822. /**
  49823. * Interpolates a quaternion using a spherical linear interpolation
  49824. * @param startValue Start value of the animation curve
  49825. * @param endValue End value of the animation curve
  49826. * @param gradient Scalar amount to interpolate
  49827. * @returns Interpolated quaternion value
  49828. */
  49829. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49830. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49831. };
  49832. /**
  49833. * Interpolates a quaternion cubically
  49834. * @param startValue Start value of the animation curve
  49835. * @param outTangent End tangent of the animation curve
  49836. * @param endValue End value of the animation curve
  49837. * @param inTangent Start tangent of the animation curve
  49838. * @param gradient Scalar amount to interpolate
  49839. * @returns Interpolated quaternion value
  49840. */
  49841. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49842. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49843. };
  49844. /**
  49845. * Interpolates a Vector3 linearl
  49846. * @param startValue Start value of the animation curve
  49847. * @param endValue End value of the animation curve
  49848. * @param gradient Scalar amount to interpolate
  49849. * @returns Interpolated scalar value
  49850. */
  49851. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49852. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49853. };
  49854. /**
  49855. * Interpolates a Vector3 cubically
  49856. * @param startValue Start value of the animation curve
  49857. * @param outTangent End tangent of the animation
  49858. * @param endValue End value of the animation curve
  49859. * @param inTangent Start tangent of the animation curve
  49860. * @param gradient Scalar amount to interpolate
  49861. * @returns InterpolatedVector3 value
  49862. */
  49863. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49864. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49865. };
  49866. /**
  49867. * Interpolates a Vector2 linearly
  49868. * @param startValue Start value of the animation curve
  49869. * @param endValue End value of the animation curve
  49870. * @param gradient Scalar amount to interpolate
  49871. * @returns Interpolated Vector2 value
  49872. */
  49873. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49874. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49875. };
  49876. /**
  49877. * Interpolates a Vector2 cubically
  49878. * @param startValue Start value of the animation curve
  49879. * @param outTangent End tangent of the animation
  49880. * @param endValue End value of the animation curve
  49881. * @param inTangent Start tangent of the animation curve
  49882. * @param gradient Scalar amount to interpolate
  49883. * @returns Interpolated Vector2 value
  49884. */
  49885. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49886. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49887. };
  49888. /**
  49889. * Interpolates a size linearly
  49890. * @param startValue Start value of the animation curve
  49891. * @param endValue End value of the animation curve
  49892. * @param gradient Scalar amount to interpolate
  49893. * @returns Interpolated Size value
  49894. */
  49895. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49896. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49897. };
  49898. /**
  49899. * Interpolates a Color3 linearly
  49900. * @param startValue Start value of the animation curve
  49901. * @param endValue End value of the animation curve
  49902. * @param gradient Scalar amount to interpolate
  49903. * @returns Interpolated Color3 value
  49904. */
  49905. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49906. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49907. };
  49908. /**
  49909. * @hidden Internal use only
  49910. */
  49911. Animation.prototype._getKeyValue = function (value) {
  49912. if (typeof value === "function") {
  49913. return value();
  49914. }
  49915. return value;
  49916. };
  49917. /**
  49918. * @hidden Internal use only
  49919. */
  49920. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49921. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49922. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49923. }
  49924. var keys = this.getKeys();
  49925. // Try to get a hash to find the right key
  49926. 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));
  49927. if (keys[startKeyIndex].frame >= currentFrame) {
  49928. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49929. startKeyIndex--;
  49930. }
  49931. }
  49932. for (var key = startKeyIndex; key < keys.length; key++) {
  49933. var endKey = keys[key + 1];
  49934. if (endKey.frame >= currentFrame) {
  49935. var startKey = keys[key];
  49936. var startValue = this._getKeyValue(startKey.value);
  49937. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49938. return startValue;
  49939. }
  49940. var endValue = this._getKeyValue(endKey.value);
  49941. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49942. var frameDelta = endKey.frame - startKey.frame;
  49943. // gradient : percent of currentFrame between the frame inf and the frame sup
  49944. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49945. // check for easingFunction and correction of gradient
  49946. var easingFunction = this.getEasingFunction();
  49947. if (easingFunction != null) {
  49948. gradient = easingFunction.ease(gradient);
  49949. }
  49950. switch (this.dataType) {
  49951. // Float
  49952. case Animation.ANIMATIONTYPE_FLOAT:
  49953. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49954. switch (loopMode) {
  49955. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49956. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49957. return floatValue;
  49958. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49959. return offsetValue * repeatCount + floatValue;
  49960. }
  49961. break;
  49962. // Quaternion
  49963. case Animation.ANIMATIONTYPE_QUATERNION:
  49964. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49965. switch (loopMode) {
  49966. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49967. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49968. return quatValue;
  49969. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49970. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49971. }
  49972. return quatValue;
  49973. // Vector3
  49974. case Animation.ANIMATIONTYPE_VECTOR3:
  49975. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49976. switch (loopMode) {
  49977. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49978. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49979. return vec3Value;
  49980. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49981. return vec3Value.add(offsetValue.scale(repeatCount));
  49982. }
  49983. // Vector2
  49984. case Animation.ANIMATIONTYPE_VECTOR2:
  49985. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49986. switch (loopMode) {
  49987. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49988. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49989. return vec2Value;
  49990. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49991. return vec2Value.add(offsetValue.scale(repeatCount));
  49992. }
  49993. // Size
  49994. case Animation.ANIMATIONTYPE_SIZE:
  49995. switch (loopMode) {
  49996. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49997. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49998. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49999. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50000. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50001. }
  50002. // Color3
  50003. case Animation.ANIMATIONTYPE_COLOR3:
  50004. switch (loopMode) {
  50005. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50006. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50007. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50008. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50009. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50010. }
  50011. // Matrix
  50012. case Animation.ANIMATIONTYPE_MATRIX:
  50013. switch (loopMode) {
  50014. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50015. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50016. if (Animation.AllowMatricesInterpolation) {
  50017. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50018. }
  50019. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50020. return startValue;
  50021. }
  50022. default:
  50023. break;
  50024. }
  50025. break;
  50026. }
  50027. }
  50028. return this._getKeyValue(keys[keys.length - 1].value);
  50029. };
  50030. /**
  50031. * Defines the function to use to interpolate matrices
  50032. * @param startValue defines the start matrix
  50033. * @param endValue defines the end matrix
  50034. * @param gradient defines the gradient between both matrices
  50035. * @param result defines an optional target matrix where to store the interpolation
  50036. * @returns the interpolated matrix
  50037. */
  50038. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50039. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50040. if (result) {
  50041. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50042. return result;
  50043. }
  50044. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50045. }
  50046. if (result) {
  50047. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50048. return result;
  50049. }
  50050. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50051. };
  50052. /**
  50053. * Makes a copy of the animation
  50054. * @returns Cloned animation
  50055. */
  50056. Animation.prototype.clone = function () {
  50057. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50058. clone.enableBlending = this.enableBlending;
  50059. clone.blendingSpeed = this.blendingSpeed;
  50060. if (this._keys) {
  50061. clone.setKeys(this._keys);
  50062. }
  50063. if (this._ranges) {
  50064. clone._ranges = {};
  50065. for (var name in this._ranges) {
  50066. var range = this._ranges[name];
  50067. if (!range) {
  50068. continue;
  50069. }
  50070. clone._ranges[name] = range.clone();
  50071. }
  50072. }
  50073. return clone;
  50074. };
  50075. /**
  50076. * Sets the key frames of the animation
  50077. * @param values The animation key frames to set
  50078. */
  50079. Animation.prototype.setKeys = function (values) {
  50080. this._keys = values.slice(0);
  50081. };
  50082. /**
  50083. * Serializes the animation to an object
  50084. * @returns Serialized object
  50085. */
  50086. Animation.prototype.serialize = function () {
  50087. var serializationObject = {};
  50088. serializationObject.name = this.name;
  50089. serializationObject.property = this.targetProperty;
  50090. serializationObject.framePerSecond = this.framePerSecond;
  50091. serializationObject.dataType = this.dataType;
  50092. serializationObject.loopBehavior = this.loopMode;
  50093. serializationObject.enableBlending = this.enableBlending;
  50094. serializationObject.blendingSpeed = this.blendingSpeed;
  50095. var dataType = this.dataType;
  50096. serializationObject.keys = [];
  50097. var keys = this.getKeys();
  50098. for (var index = 0; index < keys.length; index++) {
  50099. var animationKey = keys[index];
  50100. var key = {};
  50101. key.frame = animationKey.frame;
  50102. switch (dataType) {
  50103. case Animation.ANIMATIONTYPE_FLOAT:
  50104. key.values = [animationKey.value];
  50105. break;
  50106. case Animation.ANIMATIONTYPE_QUATERNION:
  50107. case Animation.ANIMATIONTYPE_MATRIX:
  50108. case Animation.ANIMATIONTYPE_VECTOR3:
  50109. case Animation.ANIMATIONTYPE_COLOR3:
  50110. key.values = animationKey.value.asArray();
  50111. break;
  50112. }
  50113. serializationObject.keys.push(key);
  50114. }
  50115. serializationObject.ranges = [];
  50116. for (var name in this._ranges) {
  50117. var source = this._ranges[name];
  50118. if (!source) {
  50119. continue;
  50120. }
  50121. var range = {};
  50122. range.name = name;
  50123. range.from = source.from;
  50124. range.to = source.to;
  50125. serializationObject.ranges.push(range);
  50126. }
  50127. return serializationObject;
  50128. };
  50129. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50130. /**
  50131. * Get the float animation type
  50132. */
  50133. get: function () {
  50134. return Animation._ANIMATIONTYPE_FLOAT;
  50135. },
  50136. enumerable: true,
  50137. configurable: true
  50138. });
  50139. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50140. /**
  50141. * Get the Vector3 animation type
  50142. */
  50143. get: function () {
  50144. return Animation._ANIMATIONTYPE_VECTOR3;
  50145. },
  50146. enumerable: true,
  50147. configurable: true
  50148. });
  50149. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50150. /**
  50151. * Get the Vectpr2 animation type
  50152. */
  50153. get: function () {
  50154. return Animation._ANIMATIONTYPE_VECTOR2;
  50155. },
  50156. enumerable: true,
  50157. configurable: true
  50158. });
  50159. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50160. /**
  50161. * Get the Size animation type
  50162. */
  50163. get: function () {
  50164. return Animation._ANIMATIONTYPE_SIZE;
  50165. },
  50166. enumerable: true,
  50167. configurable: true
  50168. });
  50169. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50170. /**
  50171. * Get the Quaternion animation type
  50172. */
  50173. get: function () {
  50174. return Animation._ANIMATIONTYPE_QUATERNION;
  50175. },
  50176. enumerable: true,
  50177. configurable: true
  50178. });
  50179. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50180. /**
  50181. * Get the Matrix animation type
  50182. */
  50183. get: function () {
  50184. return Animation._ANIMATIONTYPE_MATRIX;
  50185. },
  50186. enumerable: true,
  50187. configurable: true
  50188. });
  50189. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50190. /**
  50191. * Get the Color3 animation type
  50192. */
  50193. get: function () {
  50194. return Animation._ANIMATIONTYPE_COLOR3;
  50195. },
  50196. enumerable: true,
  50197. configurable: true
  50198. });
  50199. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50200. /**
  50201. * Get the Relative Loop Mode
  50202. */
  50203. get: function () {
  50204. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50205. },
  50206. enumerable: true,
  50207. configurable: true
  50208. });
  50209. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50210. /**
  50211. * Get the Cycle Loop Mode
  50212. */
  50213. get: function () {
  50214. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50215. },
  50216. enumerable: true,
  50217. configurable: true
  50218. });
  50219. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50220. /**
  50221. * Get the Constant Loop Mode
  50222. */
  50223. get: function () {
  50224. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50225. },
  50226. enumerable: true,
  50227. configurable: true
  50228. });
  50229. /** @hidden */
  50230. Animation._UniversalLerp = function (left, right, amount) {
  50231. var constructor = left.constructor;
  50232. if (constructor.Lerp) { // Lerp supported
  50233. return constructor.Lerp(left, right, amount);
  50234. }
  50235. else if (constructor.Slerp) { // Slerp supported
  50236. return constructor.Slerp(left, right, amount);
  50237. }
  50238. else if (left.toFixed) { // Number
  50239. return left * (1.0 - amount) + amount * right;
  50240. }
  50241. else { // Blending not supported
  50242. return right;
  50243. }
  50244. };
  50245. /**
  50246. * Parses an animation object and creates an animation
  50247. * @param parsedAnimation Parsed animation object
  50248. * @returns Animation object
  50249. */
  50250. Animation.Parse = function (parsedAnimation) {
  50251. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50252. var dataType = parsedAnimation.dataType;
  50253. var keys = [];
  50254. var data;
  50255. var index;
  50256. if (parsedAnimation.enableBlending) {
  50257. animation.enableBlending = parsedAnimation.enableBlending;
  50258. }
  50259. if (parsedAnimation.blendingSpeed) {
  50260. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50261. }
  50262. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50263. var key = parsedAnimation.keys[index];
  50264. var inTangent;
  50265. var outTangent;
  50266. switch (dataType) {
  50267. case Animation.ANIMATIONTYPE_FLOAT:
  50268. data = key.values[0];
  50269. if (key.values.length >= 1) {
  50270. inTangent = key.values[1];
  50271. }
  50272. if (key.values.length >= 2) {
  50273. outTangent = key.values[2];
  50274. }
  50275. break;
  50276. case Animation.ANIMATIONTYPE_QUATERNION:
  50277. data = BABYLON.Quaternion.FromArray(key.values);
  50278. if (key.values.length >= 8) {
  50279. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50280. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50281. inTangent = _inTangent;
  50282. }
  50283. }
  50284. if (key.values.length >= 12) {
  50285. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50286. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50287. outTangent = _outTangent;
  50288. }
  50289. }
  50290. break;
  50291. case Animation.ANIMATIONTYPE_MATRIX:
  50292. data = BABYLON.Matrix.FromArray(key.values);
  50293. break;
  50294. case Animation.ANIMATIONTYPE_COLOR3:
  50295. data = BABYLON.Color3.FromArray(key.values);
  50296. break;
  50297. case Animation.ANIMATIONTYPE_VECTOR3:
  50298. default:
  50299. data = BABYLON.Vector3.FromArray(key.values);
  50300. break;
  50301. }
  50302. var keyData = {};
  50303. keyData.frame = key.frame;
  50304. keyData.value = data;
  50305. if (inTangent != undefined) {
  50306. keyData.inTangent = inTangent;
  50307. }
  50308. if (outTangent != undefined) {
  50309. keyData.outTangent = outTangent;
  50310. }
  50311. keys.push(keyData);
  50312. }
  50313. animation.setKeys(keys);
  50314. if (parsedAnimation.ranges) {
  50315. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50316. data = parsedAnimation.ranges[index];
  50317. animation.createRange(data.name, data.from, data.to);
  50318. }
  50319. }
  50320. return animation;
  50321. };
  50322. /**
  50323. * Appends the serialized animations from the source animations
  50324. * @param source Source containing the animations
  50325. * @param destination Target to store the animations
  50326. */
  50327. Animation.AppendSerializedAnimations = function (source, destination) {
  50328. if (source.animations) {
  50329. destination.animations = [];
  50330. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50331. var animation = source.animations[animationIndex];
  50332. destination.animations.push(animation.serialize());
  50333. }
  50334. }
  50335. };
  50336. /**
  50337. * Use matrix interpolation instead of using direct key value when animating matrices
  50338. */
  50339. Animation.AllowMatricesInterpolation = false;
  50340. /**
  50341. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50342. */
  50343. Animation.AllowMatrixDecomposeForInterpolation = true;
  50344. // Statics
  50345. /**
  50346. * Float animation type
  50347. */
  50348. Animation._ANIMATIONTYPE_FLOAT = 0;
  50349. /**
  50350. * Vector3 animation type
  50351. */
  50352. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50353. /**
  50354. * Quaternion animation type
  50355. */
  50356. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50357. /**
  50358. * Matrix animation type
  50359. */
  50360. Animation._ANIMATIONTYPE_MATRIX = 3;
  50361. /**
  50362. * Color3 animation type
  50363. */
  50364. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50365. /**
  50366. * Vector2 animation type
  50367. */
  50368. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50369. /**
  50370. * Size animation type
  50371. */
  50372. Animation._ANIMATIONTYPE_SIZE = 6;
  50373. /**
  50374. * Relative Loop Mode
  50375. */
  50376. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50377. /**
  50378. * Cycle Loop Mode
  50379. */
  50380. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50381. /**
  50382. * Constant Loop Mode
  50383. */
  50384. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50385. return Animation;
  50386. }());
  50387. BABYLON.Animation = Animation;
  50388. })(BABYLON || (BABYLON = {}));
  50389. //# sourceMappingURL=babylon.animation.js.map
  50390. var BABYLON;
  50391. (function (BABYLON) {
  50392. /**
  50393. * This class defines the direct association between an animation and a target
  50394. */
  50395. var TargetedAnimation = /** @class */ (function () {
  50396. function TargetedAnimation() {
  50397. }
  50398. return TargetedAnimation;
  50399. }());
  50400. BABYLON.TargetedAnimation = TargetedAnimation;
  50401. /**
  50402. * Use this class to create coordinated animations on multiple targets
  50403. */
  50404. var AnimationGroup = /** @class */ (function () {
  50405. function AnimationGroup(name, scene) {
  50406. if (scene === void 0) { scene = null; }
  50407. this.name = name;
  50408. this._targetedAnimations = new Array();
  50409. this._animatables = new Array();
  50410. this._from = Number.MAX_VALUE;
  50411. this._to = -Number.MAX_VALUE;
  50412. this._speedRatio = 1;
  50413. this.onAnimationEndObservable = new BABYLON.Observable();
  50414. /**
  50415. * This observable will notify when all animations have ended.
  50416. */
  50417. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50419. this._scene.animationGroups.push(this);
  50420. }
  50421. Object.defineProperty(AnimationGroup.prototype, "from", {
  50422. /**
  50423. * Gets the first frame
  50424. */
  50425. get: function () {
  50426. return this._from;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. Object.defineProperty(AnimationGroup.prototype, "to", {
  50432. /**
  50433. * Gets the last frame
  50434. */
  50435. get: function () {
  50436. return this._to;
  50437. },
  50438. enumerable: true,
  50439. configurable: true
  50440. });
  50441. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50442. /**
  50443. * Define if the animations are started
  50444. */
  50445. get: function () {
  50446. return this._isStarted;
  50447. },
  50448. enumerable: true,
  50449. configurable: true
  50450. });
  50451. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50452. /**
  50453. * Gets or sets the speed ratio to use for all animations
  50454. */
  50455. get: function () {
  50456. return this._speedRatio;
  50457. },
  50458. /**
  50459. * Gets or sets the speed ratio to use for all animations
  50460. */
  50461. set: function (value) {
  50462. if (this._speedRatio === value) {
  50463. return;
  50464. }
  50465. this._speedRatio = value;
  50466. for (var index = 0; index < this._animatables.length; index++) {
  50467. var animatable = this._animatables[index];
  50468. animatable.speedRatio = this._speedRatio;
  50469. }
  50470. },
  50471. enumerable: true,
  50472. configurable: true
  50473. });
  50474. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50475. /**
  50476. * Gets the targeted animations for this animation group
  50477. */
  50478. get: function () {
  50479. return this._targetedAnimations;
  50480. },
  50481. enumerable: true,
  50482. configurable: true
  50483. });
  50484. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50485. /**
  50486. * returning the list of animatables controlled by this animation group.
  50487. */
  50488. get: function () {
  50489. return this._animatables;
  50490. },
  50491. enumerable: true,
  50492. configurable: true
  50493. });
  50494. /**
  50495. * Add an animation (with its target) in the group
  50496. * @param animation defines the animation we want to add
  50497. * @param target defines the target of the animation
  50498. * @returns the {BABYLON.TargetedAnimation} object
  50499. */
  50500. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50501. var targetedAnimation = {
  50502. animation: animation,
  50503. target: target
  50504. };
  50505. var keys = animation.getKeys();
  50506. if (this._from > keys[0].frame) {
  50507. this._from = keys[0].frame;
  50508. }
  50509. if (this._to < keys[keys.length - 1].frame) {
  50510. this._to = keys[keys.length - 1].frame;
  50511. }
  50512. this._targetedAnimations.push(targetedAnimation);
  50513. return targetedAnimation;
  50514. };
  50515. /**
  50516. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50517. * It can add constant keys at begin or end
  50518. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50519. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50520. */
  50521. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50522. if (beginFrame === void 0) { beginFrame = null; }
  50523. if (endFrame === void 0) { endFrame = null; }
  50524. if (beginFrame == null)
  50525. beginFrame = this._from;
  50526. if (endFrame == null)
  50527. endFrame = this._to;
  50528. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50529. var targetedAnimation = this._targetedAnimations[index];
  50530. var keys = targetedAnimation.animation.getKeys();
  50531. var startKey = keys[0];
  50532. var endKey = keys[keys.length - 1];
  50533. if (startKey.frame > beginFrame) {
  50534. var newKey = {
  50535. frame: beginFrame,
  50536. value: startKey.value,
  50537. inTangent: startKey.inTangent,
  50538. outTangent: startKey.outTangent,
  50539. interpolation: startKey.interpolation
  50540. };
  50541. keys.splice(0, 0, newKey);
  50542. }
  50543. if (endKey.frame < endFrame) {
  50544. var newKey = {
  50545. frame: endFrame,
  50546. value: endKey.value,
  50547. inTangent: endKey.outTangent,
  50548. outTangent: endKey.outTangent,
  50549. interpolation: endKey.interpolation
  50550. };
  50551. keys.push(newKey);
  50552. }
  50553. }
  50554. this._from = beginFrame;
  50555. this._to = endFrame;
  50556. return this;
  50557. };
  50558. /**
  50559. * Start all animations on given targets
  50560. * @param loop defines if animations must loop
  50561. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50562. * @param from defines the from key (optional)
  50563. * @param to defines the to key (optional)
  50564. * @returns the current animation group
  50565. */
  50566. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50567. var _this = this;
  50568. if (loop === void 0) { loop = false; }
  50569. if (speedRatio === void 0) { speedRatio = 1; }
  50570. if (this._isStarted || this._targetedAnimations.length === 0) {
  50571. return this;
  50572. }
  50573. var _loop_1 = function (targetedAnimation) {
  50574. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50575. animatable.onAnimationEnd = function () {
  50576. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50577. _this._checkAnimationGroupEnded(animatable);
  50578. };
  50579. this_1._animatables.push(animatable);
  50580. };
  50581. var this_1 = this;
  50582. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50583. var targetedAnimation = _a[_i];
  50584. _loop_1(targetedAnimation);
  50585. }
  50586. this._speedRatio = speedRatio;
  50587. this._isStarted = true;
  50588. return this;
  50589. };
  50590. /**
  50591. * Pause all animations
  50592. */
  50593. AnimationGroup.prototype.pause = function () {
  50594. if (!this._isStarted) {
  50595. return this;
  50596. }
  50597. for (var index = 0; index < this._animatables.length; index++) {
  50598. var animatable = this._animatables[index];
  50599. animatable.pause();
  50600. }
  50601. return this;
  50602. };
  50603. /**
  50604. * Play all animations to initial state
  50605. * This function will start() the animations if they were not started or will restart() them if they were paused
  50606. * @param loop defines if animations must loop
  50607. */
  50608. AnimationGroup.prototype.play = function (loop) {
  50609. // only if all animatables are ready and exist
  50610. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50611. if (loop !== undefined) {
  50612. for (var index = 0; index < this._animatables.length; index++) {
  50613. var animatable = this._animatables[index];
  50614. animatable.loopAnimation = loop;
  50615. }
  50616. }
  50617. this.restart();
  50618. }
  50619. else {
  50620. this.stop();
  50621. this.start(loop, this._speedRatio);
  50622. }
  50623. return this;
  50624. };
  50625. /**
  50626. * Reset all animations to initial state
  50627. */
  50628. AnimationGroup.prototype.reset = function () {
  50629. if (!this._isStarted) {
  50630. return this;
  50631. }
  50632. for (var index = 0; index < this._animatables.length; index++) {
  50633. var animatable = this._animatables[index];
  50634. animatable.reset();
  50635. }
  50636. return this;
  50637. };
  50638. /**
  50639. * Restart animations from key 0
  50640. */
  50641. AnimationGroup.prototype.restart = function () {
  50642. if (!this._isStarted) {
  50643. return this;
  50644. }
  50645. for (var index = 0; index < this._animatables.length; index++) {
  50646. var animatable = this._animatables[index];
  50647. animatable.restart();
  50648. }
  50649. return this;
  50650. };
  50651. /**
  50652. * Stop all animations
  50653. */
  50654. AnimationGroup.prototype.stop = function () {
  50655. if (!this._isStarted) {
  50656. return this;
  50657. }
  50658. var list = this._animatables.slice();
  50659. for (var index = 0; index < list.length; index++) {
  50660. list[index].stop();
  50661. }
  50662. this._isStarted = false;
  50663. return this;
  50664. };
  50665. /**
  50666. * Set animation weight for all animatables
  50667. * @param weight defines the weight to use
  50668. * @return the animationGroup
  50669. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50670. */
  50671. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50672. for (var index = 0; index < this._animatables.length; index++) {
  50673. var animatable = this._animatables[index];
  50674. animatable.weight = weight;
  50675. }
  50676. return this;
  50677. };
  50678. /**
  50679. * Synchronize and normalize all animatables with a source animatable
  50680. * @param root defines the root animatable to synchronize with
  50681. * @return the animationGroup
  50682. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50683. */
  50684. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50685. for (var index = 0; index < this._animatables.length; index++) {
  50686. var animatable = this._animatables[index];
  50687. animatable.syncWith(root);
  50688. }
  50689. return this;
  50690. };
  50691. /**
  50692. * Goes to a specific frame in this animation group
  50693. * @param frame the frame number to go to
  50694. * @return the animationGroup
  50695. */
  50696. AnimationGroup.prototype.goToFrame = function (frame) {
  50697. if (!this._isStarted) {
  50698. return this;
  50699. }
  50700. for (var index = 0; index < this._animatables.length; index++) {
  50701. var animatable = this._animatables[index];
  50702. animatable.goToFrame(frame);
  50703. }
  50704. return this;
  50705. };
  50706. /**
  50707. * Dispose all associated resources
  50708. */
  50709. AnimationGroup.prototype.dispose = function () {
  50710. this._targetedAnimations = [];
  50711. this._animatables = [];
  50712. var index = this._scene.animationGroups.indexOf(this);
  50713. if (index > -1) {
  50714. this._scene.animationGroups.splice(index, 1);
  50715. }
  50716. };
  50717. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50718. // animatable should be taken out of the array
  50719. var idx = this._animatables.indexOf(animatable);
  50720. if (idx > -1) {
  50721. this._animatables.splice(idx, 1);
  50722. }
  50723. // all animatables were removed? animation group ended!
  50724. if (this._animatables.length === 0) {
  50725. this._isStarted = false;
  50726. this.onAnimationGroupEndObservable.notifyObservers(this);
  50727. }
  50728. };
  50729. return AnimationGroup;
  50730. }());
  50731. BABYLON.AnimationGroup = AnimationGroup;
  50732. })(BABYLON || (BABYLON = {}));
  50733. //# sourceMappingURL=babylon.animationGroup.js.map
  50734. var BABYLON;
  50735. (function (BABYLON) {
  50736. /**
  50737. * Defines a runtime animation
  50738. */
  50739. var RuntimeAnimation = /** @class */ (function () {
  50740. /**
  50741. * Create a new RuntimeAnimation object
  50742. * @param target defines the target of the animation
  50743. * @param animation defines the source animation object
  50744. * @param scene defines the hosting scene
  50745. * @param host defines the initiating Animatable
  50746. */
  50747. function RuntimeAnimation(target, animation, scene, host) {
  50748. var _this = this;
  50749. this._events = new Array();
  50750. /**
  50751. * The current frame of the runtime animation
  50752. */
  50753. this._currentFrame = 0;
  50754. /**
  50755. * The original value of the runtime animation
  50756. */
  50757. this._originalValue = new Array();
  50758. /**
  50759. * The offsets cache of the runtime animation
  50760. */
  50761. this._offsetsCache = {};
  50762. /**
  50763. * The high limits cache of the runtime animation
  50764. */
  50765. this._highLimitsCache = {};
  50766. /**
  50767. * Specifies if the runtime animation has been stopped
  50768. */
  50769. this._stopped = false;
  50770. /**
  50771. * The blending factor of the runtime animation
  50772. */
  50773. this._blendingFactor = 0;
  50774. /**
  50775. * The target path of the runtime animation
  50776. */
  50777. this._targetPath = "";
  50778. /**
  50779. * The weight of the runtime animation
  50780. */
  50781. this._weight = 1.0;
  50782. /**
  50783. * The ratio offset of the runtime animation
  50784. */
  50785. this._ratioOffset = 0;
  50786. /**
  50787. * The previous delay of the runtime animation
  50788. */
  50789. this._previousDelay = 0;
  50790. /**
  50791. * The previous ratio of the runtime animation
  50792. */
  50793. this._previousRatio = 0;
  50794. this._animation = animation;
  50795. this._target = target;
  50796. this._scene = scene;
  50797. this._host = host;
  50798. animation._runtimeAnimations.push(this);
  50799. // Cloning events locally
  50800. var events = animation.getEvents();
  50801. if (events && events.length > 0) {
  50802. events.forEach(function (e) {
  50803. _this._events.push(e._clone());
  50804. });
  50805. }
  50806. }
  50807. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50808. /**
  50809. * Gets the current frame of the runtime animation
  50810. */
  50811. get: function () {
  50812. return this._currentFrame;
  50813. },
  50814. enumerable: true,
  50815. configurable: true
  50816. });
  50817. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50818. /**
  50819. * Gets the weight of the runtime animation
  50820. */
  50821. get: function () {
  50822. return this._weight;
  50823. },
  50824. enumerable: true,
  50825. configurable: true
  50826. });
  50827. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50828. /**
  50829. * Gets the current value of the runtime animation
  50830. */
  50831. get: function () {
  50832. return this._currentValue;
  50833. },
  50834. enumerable: true,
  50835. configurable: true
  50836. });
  50837. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50838. /**
  50839. * Gets the target path of the runtime animation
  50840. */
  50841. get: function () {
  50842. return this._targetPath;
  50843. },
  50844. enumerable: true,
  50845. configurable: true
  50846. });
  50847. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50848. /**
  50849. * Gets the actual target of the runtime animation
  50850. */
  50851. get: function () {
  50852. return this._activeTarget;
  50853. },
  50854. enumerable: true,
  50855. configurable: true
  50856. });
  50857. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50858. /**
  50859. * Gets the animation from the runtime animation
  50860. */
  50861. get: function () {
  50862. return this._animation;
  50863. },
  50864. enumerable: true,
  50865. configurable: true
  50866. });
  50867. /**
  50868. * Resets the runtime animation to the beginning
  50869. * @param restoreOriginal defines whether to restore the target property to the original value
  50870. */
  50871. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50872. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50873. if (restoreOriginal) {
  50874. if (this._target instanceof Array) {
  50875. var index = 0;
  50876. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50877. var target = _a[_i];
  50878. if (this._originalValue[index] !== undefined) {
  50879. this._setValue(target, this._originalValue[index], -1);
  50880. }
  50881. index++;
  50882. }
  50883. }
  50884. else {
  50885. if (this._originalValue[0] !== undefined) {
  50886. this._setValue(this._target, this._originalValue[0], -1);
  50887. }
  50888. }
  50889. }
  50890. this._offsetsCache = {};
  50891. this._highLimitsCache = {};
  50892. this._currentFrame = 0;
  50893. this._blendingFactor = 0;
  50894. this._originalValue = new Array();
  50895. // Events
  50896. for (var index = 0; index < this._events.length; index++) {
  50897. this._events[index].isDone = false;
  50898. }
  50899. };
  50900. /**
  50901. * Specifies if the runtime animation is stopped
  50902. * @returns Boolean specifying if the runtime animation is stopped
  50903. */
  50904. RuntimeAnimation.prototype.isStopped = function () {
  50905. return this._stopped;
  50906. };
  50907. /**
  50908. * Disposes of the runtime animation
  50909. */
  50910. RuntimeAnimation.prototype.dispose = function () {
  50911. var index = this._animation.runtimeAnimations.indexOf(this);
  50912. if (index > -1) {
  50913. this._animation.runtimeAnimations.splice(index, 1);
  50914. }
  50915. };
  50916. /**
  50917. * Interpolates the animation from the current frame
  50918. * @param currentFrame The frame to interpolate the animation to
  50919. * @param repeatCount The number of times that the animation should loop
  50920. * @param loopMode The type of looping mode to use
  50921. * @param offsetValue Animation offset value
  50922. * @param highLimitValue The high limit value
  50923. * @returns The interpolated value
  50924. */
  50925. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50926. this._currentFrame = currentFrame;
  50927. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50928. this._workValue = BABYLON.Matrix.Zero();
  50929. }
  50930. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50931. };
  50932. /**
  50933. * Apply the interpolated value to the target
  50934. * @param currentValue defines the value computed by the animation
  50935. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50936. */
  50937. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50938. if (weight === void 0) { weight = 1.0; }
  50939. if (this._target instanceof Array) {
  50940. var index = 0;
  50941. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50942. var target = _a[_i];
  50943. this._setValue(target, currentValue, weight, index);
  50944. index++;
  50945. }
  50946. }
  50947. else {
  50948. this._setValue(this._target, currentValue, weight);
  50949. }
  50950. };
  50951. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50952. if (targetIndex === void 0) { targetIndex = 0; }
  50953. // Set value
  50954. var path;
  50955. var destination;
  50956. var targetPropertyPath = this._animation.targetPropertyPath;
  50957. if (targetPropertyPath.length > 1) {
  50958. var property = target[targetPropertyPath[0]];
  50959. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50960. property = property[targetPropertyPath[index]];
  50961. }
  50962. path = targetPropertyPath[targetPropertyPath.length - 1];
  50963. destination = property;
  50964. }
  50965. else {
  50966. path = targetPropertyPath[0];
  50967. destination = target;
  50968. }
  50969. this._targetPath = path;
  50970. this._activeTarget = destination;
  50971. this._weight = weight;
  50972. if (this._originalValue[targetIndex] === undefined) {
  50973. var originalValue = void 0;
  50974. if (destination.getRestPose && path === "_matrix") { // For bones
  50975. originalValue = destination.getRestPose();
  50976. }
  50977. else {
  50978. originalValue = destination[path];
  50979. }
  50980. if (originalValue && originalValue.clone) {
  50981. this._originalValue[targetIndex] = originalValue.clone();
  50982. }
  50983. else {
  50984. this._originalValue[targetIndex] = originalValue;
  50985. }
  50986. }
  50987. // Blending
  50988. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50989. if (enableBlending && this._blendingFactor <= 1.0) {
  50990. if (!this._originalBlendValue) {
  50991. var originalValue = destination[path];
  50992. if (originalValue.clone) {
  50993. this._originalBlendValue = originalValue.clone();
  50994. }
  50995. else {
  50996. this._originalBlendValue = originalValue;
  50997. }
  50998. }
  50999. if (this._originalBlendValue.m) { // Matrix
  51000. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51001. if (this._currentValue) {
  51002. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51003. }
  51004. else {
  51005. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51006. }
  51007. }
  51008. else {
  51009. if (this._currentValue) {
  51010. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51011. }
  51012. else {
  51013. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51014. }
  51015. }
  51016. }
  51017. else {
  51018. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51019. }
  51020. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51021. this._blendingFactor += blendingSpeed;
  51022. }
  51023. else {
  51024. this._currentValue = currentValue;
  51025. }
  51026. if (weight !== -1.0) {
  51027. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51028. }
  51029. else {
  51030. destination[path] = this._currentValue;
  51031. }
  51032. if (target.markAsDirty) {
  51033. target.markAsDirty(this._animation.targetProperty);
  51034. }
  51035. };
  51036. /**
  51037. * Gets the loop pmode of the runtime animation
  51038. * @returns Loop Mode
  51039. */
  51040. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51041. if (this._target && this._target.animationPropertiesOverride) {
  51042. return this._target.animationPropertiesOverride.loopMode;
  51043. }
  51044. return this._animation.loopMode;
  51045. };
  51046. /**
  51047. * Move the current animation to a given frame
  51048. * @param frame defines the frame to move to
  51049. */
  51050. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51051. var keys = this._animation.getKeys();
  51052. if (frame < keys[0].frame) {
  51053. frame = keys[0].frame;
  51054. }
  51055. else if (frame > keys[keys.length - 1].frame) {
  51056. frame = keys[keys.length - 1].frame;
  51057. }
  51058. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51059. this.setValue(currentValue, -1);
  51060. };
  51061. /**
  51062. * @hidden Internal use only
  51063. */
  51064. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51065. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51066. this._ratioOffset = this._previousRatio - newRatio;
  51067. };
  51068. /**
  51069. * Execute the current animation
  51070. * @param delay defines the delay to add to the current frame
  51071. * @param from defines the lower bound of the animation range
  51072. * @param to defines the upper bound of the animation range
  51073. * @param loop defines if the current animation must loop
  51074. * @param speedRatio defines the current speed ratio
  51075. * @param weight defines the weight of the animation (default is -1 so no weight)
  51076. * @returns a boolean indicating if the animation has ended
  51077. */
  51078. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51079. if (weight === void 0) { weight = -1.0; }
  51080. var targetPropertyPath = this._animation.targetPropertyPath;
  51081. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51082. this._stopped = true;
  51083. return false;
  51084. }
  51085. var keys = this._animation.getKeys();
  51086. // Return immediately if there is only one key frame.
  51087. if (keys.length === 1) {
  51088. this.setValue(keys[0].value, weight);
  51089. return !loop;
  51090. }
  51091. var returnValue = true;
  51092. // Adding a start key at frame 0 if missing
  51093. if (keys[0].frame !== 0) {
  51094. var newKey = { frame: 0, value: keys[0].value };
  51095. keys.splice(0, 0, newKey);
  51096. }
  51097. // Check limits
  51098. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51099. from = keys[0].frame;
  51100. }
  51101. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51102. to = keys[keys.length - 1].frame;
  51103. }
  51104. //to and from cannot be the same key
  51105. if (from === to) {
  51106. if (from > keys[0].frame) {
  51107. from--;
  51108. }
  51109. else if (to < keys[keys.length - 1].frame) {
  51110. to++;
  51111. }
  51112. }
  51113. // Compute ratio
  51114. var range = to - from;
  51115. var offsetValue;
  51116. // ratio represents the frame delta between from and to
  51117. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51118. var highLimitValue = 0;
  51119. this._previousDelay = delay;
  51120. this._previousRatio = ratio;
  51121. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51122. returnValue = false;
  51123. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51124. }
  51125. else {
  51126. // Get max value if required
  51127. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51128. var keyOffset = to.toString() + from.toString();
  51129. if (!this._offsetsCache[keyOffset]) {
  51130. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51131. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51132. switch (this._animation.dataType) {
  51133. // Float
  51134. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51135. this._offsetsCache[keyOffset] = toValue - fromValue;
  51136. break;
  51137. // Quaternion
  51138. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51139. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51140. break;
  51141. // Vector3
  51142. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51144. // Vector2
  51145. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51146. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51147. // Size
  51148. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51149. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51150. // Color3
  51151. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51152. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51153. default:
  51154. break;
  51155. }
  51156. this._highLimitsCache[keyOffset] = toValue;
  51157. }
  51158. highLimitValue = this._highLimitsCache[keyOffset];
  51159. offsetValue = this._offsetsCache[keyOffset];
  51160. }
  51161. }
  51162. if (offsetValue === undefined) {
  51163. switch (this._animation.dataType) {
  51164. // Float
  51165. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51166. offsetValue = 0;
  51167. break;
  51168. // Quaternion
  51169. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51170. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51171. break;
  51172. // Vector3
  51173. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51174. offsetValue = BABYLON.Vector3.Zero();
  51175. break;
  51176. // Vector2
  51177. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51178. offsetValue = BABYLON.Vector2.Zero();
  51179. break;
  51180. // Size
  51181. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51182. offsetValue = BABYLON.Size.Zero();
  51183. break;
  51184. // Color3
  51185. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51186. offsetValue = BABYLON.Color3.Black();
  51187. }
  51188. }
  51189. // Compute value
  51190. var repeatCount = (ratio / range) >> 0;
  51191. var currentFrame = returnValue ? from + ratio % range : to;
  51192. // Need to normalize?
  51193. if (this._host && this._host.syncRoot) {
  51194. var syncRoot = this._host.syncRoot;
  51195. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51196. currentFrame = from + (to - from) * hostNormalizedFrame;
  51197. }
  51198. // Reset events if looping
  51199. var events = this._events;
  51200. if (range > 0 && this.currentFrame > currentFrame ||
  51201. range < 0 && this.currentFrame < currentFrame) {
  51202. // Need to reset animation events
  51203. for (var index = 0; index < events.length; index++) {
  51204. if (!events[index].onlyOnce) {
  51205. // reset event, the animation is looping
  51206. events[index].isDone = false;
  51207. }
  51208. }
  51209. }
  51210. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51211. // Set value
  51212. this.setValue(currentValue, weight);
  51213. // Check events
  51214. for (var index = 0; index < events.length; index++) {
  51215. // Make sure current frame has passed event frame and that event frame is within the current range
  51216. // Also, handle both forward and reverse animations
  51217. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51218. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51219. var event = events[index];
  51220. if (!event.isDone) {
  51221. // If event should be done only once, remove it.
  51222. if (event.onlyOnce) {
  51223. events.splice(index, 1);
  51224. index--;
  51225. }
  51226. event.isDone = true;
  51227. event.action();
  51228. } // Don't do anything if the event has already be done.
  51229. }
  51230. }
  51231. if (!returnValue) {
  51232. this._stopped = true;
  51233. }
  51234. return returnValue;
  51235. };
  51236. return RuntimeAnimation;
  51237. }());
  51238. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51239. })(BABYLON || (BABYLON = {}));
  51240. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51241. var BABYLON;
  51242. (function (BABYLON) {
  51243. /**
  51244. * Class used to store an actual running animation
  51245. */
  51246. var Animatable = /** @class */ (function () {
  51247. /**
  51248. * Creates a new Animatable
  51249. * @param scene defines the hosting scene
  51250. * @param target defines the target object
  51251. * @param fromFrame defines the starting frame number (default is 0)
  51252. * @param toFrame defines the ending frame number (default is 100)
  51253. * @param loopAnimation defines if the animation must loop (default is false)
  51254. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51255. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51256. * @param animations defines a group of animation to add to the new Animatable
  51257. */
  51258. function Animatable(scene,
  51259. /** defines the target object */
  51260. target,
  51261. /** defines the starting frame number (default is 0) */
  51262. fromFrame,
  51263. /** defines the ending frame number (default is 100) */
  51264. toFrame,
  51265. /** defines if the animation must loop (default is false) */
  51266. loopAnimation, speedRatio,
  51267. /** defines a callback to call when animation ends if it is not looping */
  51268. onAnimationEnd, animations) {
  51269. if (fromFrame === void 0) { fromFrame = 0; }
  51270. if (toFrame === void 0) { toFrame = 100; }
  51271. if (loopAnimation === void 0) { loopAnimation = false; }
  51272. if (speedRatio === void 0) { speedRatio = 1.0; }
  51273. this.target = target;
  51274. this.fromFrame = fromFrame;
  51275. this.toFrame = toFrame;
  51276. this.loopAnimation = loopAnimation;
  51277. this.onAnimationEnd = onAnimationEnd;
  51278. this._localDelayOffset = null;
  51279. this._pausedDelay = null;
  51280. this._runtimeAnimations = new Array();
  51281. this._paused = false;
  51282. this._speedRatio = 1;
  51283. this._weight = -1.0;
  51284. /**
  51285. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51286. * This will only apply for non looping animation (default is true)
  51287. */
  51288. this.disposeOnEnd = true;
  51289. /**
  51290. * Gets a boolean indicating if the animation has started
  51291. */
  51292. this.animationStarted = false;
  51293. /**
  51294. * Observer raised when the animation ends
  51295. */
  51296. this.onAnimationEndObservable = new BABYLON.Observable();
  51297. this._scene = scene;
  51298. if (animations) {
  51299. this.appendAnimations(target, animations);
  51300. }
  51301. this._speedRatio = speedRatio;
  51302. scene._activeAnimatables.push(this);
  51303. }
  51304. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51305. /**
  51306. * Gets the root Animatable used to synchronize and normalize animations
  51307. */
  51308. get: function () {
  51309. return this._syncRoot;
  51310. },
  51311. enumerable: true,
  51312. configurable: true
  51313. });
  51314. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51315. /**
  51316. * Gets the current frame of the first RuntimeAnimation
  51317. * Used to synchronize Animatables
  51318. */
  51319. get: function () {
  51320. if (this._runtimeAnimations.length === 0) {
  51321. return 0;
  51322. }
  51323. return this._runtimeAnimations[0].currentFrame;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. Object.defineProperty(Animatable.prototype, "weight", {
  51329. /**
  51330. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51331. */
  51332. get: function () {
  51333. return this._weight;
  51334. },
  51335. set: function (value) {
  51336. if (value === -1) { // -1 is ok and means no weight
  51337. this._weight = -1;
  51338. return;
  51339. }
  51340. // Else weight must be in [0, 1] range
  51341. this._weight = Math.min(Math.max(value, 0), 1.0);
  51342. },
  51343. enumerable: true,
  51344. configurable: true
  51345. });
  51346. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51347. /**
  51348. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51349. */
  51350. get: function () {
  51351. return this._speedRatio;
  51352. },
  51353. set: function (value) {
  51354. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51355. var animation = this._runtimeAnimations[index];
  51356. animation._prepareForSpeedRatioChange(value);
  51357. }
  51358. this._speedRatio = value;
  51359. },
  51360. enumerable: true,
  51361. configurable: true
  51362. });
  51363. // Methods
  51364. /**
  51365. * Synchronize and normalize current Animatable with a source Animatable
  51366. * This is useful when using animation weights and when animations are not of the same length
  51367. * @param root defines the root Animatable to synchronize with
  51368. * @returns the current Animatable
  51369. */
  51370. Animatable.prototype.syncWith = function (root) {
  51371. this._syncRoot = root;
  51372. if (root) {
  51373. // Make sure this animatable will animate after the root
  51374. var index = this._scene._activeAnimatables.indexOf(this);
  51375. if (index > -1) {
  51376. this._scene._activeAnimatables.splice(index, 1);
  51377. this._scene._activeAnimatables.push(this);
  51378. }
  51379. }
  51380. return this;
  51381. };
  51382. /**
  51383. * Gets the list of runtime animations
  51384. * @returns an array of RuntimeAnimation
  51385. */
  51386. Animatable.prototype.getAnimations = function () {
  51387. return this._runtimeAnimations;
  51388. };
  51389. /**
  51390. * Adds more animations to the current animatable
  51391. * @param target defines the target of the animations
  51392. * @param animations defines the new animations to add
  51393. */
  51394. Animatable.prototype.appendAnimations = function (target, animations) {
  51395. for (var index = 0; index < animations.length; index++) {
  51396. var animation = animations[index];
  51397. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51398. }
  51399. };
  51400. /**
  51401. * Gets the source animation for a specific property
  51402. * @param property defines the propertyu to look for
  51403. * @returns null or the source animation for the given property
  51404. */
  51405. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51406. var runtimeAnimations = this._runtimeAnimations;
  51407. for (var index = 0; index < runtimeAnimations.length; index++) {
  51408. if (runtimeAnimations[index].animation.targetProperty === property) {
  51409. return runtimeAnimations[index].animation;
  51410. }
  51411. }
  51412. return null;
  51413. };
  51414. /**
  51415. * Gets the runtime animation for a specific property
  51416. * @param property defines the propertyu to look for
  51417. * @returns null or the runtime animation for the given property
  51418. */
  51419. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51420. var runtimeAnimations = this._runtimeAnimations;
  51421. for (var index = 0; index < runtimeAnimations.length; index++) {
  51422. if (runtimeAnimations[index].animation.targetProperty === property) {
  51423. return runtimeAnimations[index];
  51424. }
  51425. }
  51426. return null;
  51427. };
  51428. /**
  51429. * Resets the animatable to its original state
  51430. */
  51431. Animatable.prototype.reset = function () {
  51432. var runtimeAnimations = this._runtimeAnimations;
  51433. for (var index = 0; index < runtimeAnimations.length; index++) {
  51434. runtimeAnimations[index].reset(true);
  51435. }
  51436. this._localDelayOffset = null;
  51437. this._pausedDelay = null;
  51438. };
  51439. /**
  51440. * Allows the animatable to blend with current running animations
  51441. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51442. * @param blendingSpeed defines the blending speed to use
  51443. */
  51444. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51445. var runtimeAnimations = this._runtimeAnimations;
  51446. for (var index = 0; index < runtimeAnimations.length; index++) {
  51447. runtimeAnimations[index].animation.enableBlending = true;
  51448. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51449. }
  51450. };
  51451. /**
  51452. * Disable animation blending
  51453. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51454. */
  51455. Animatable.prototype.disableBlending = function () {
  51456. var runtimeAnimations = this._runtimeAnimations;
  51457. for (var index = 0; index < runtimeAnimations.length; index++) {
  51458. runtimeAnimations[index].animation.enableBlending = false;
  51459. }
  51460. };
  51461. /**
  51462. * Jump directly to a given frame
  51463. * @param frame defines the frame to jump to
  51464. */
  51465. Animatable.prototype.goToFrame = function (frame) {
  51466. var runtimeAnimations = this._runtimeAnimations;
  51467. if (runtimeAnimations[0]) {
  51468. var fps = runtimeAnimations[0].animation.framePerSecond;
  51469. var currentFrame = runtimeAnimations[0].currentFrame;
  51470. var adjustTime = frame - currentFrame;
  51471. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51472. if (this._localDelayOffset === null) {
  51473. this._localDelayOffset = 0;
  51474. }
  51475. this._localDelayOffset -= delay;
  51476. }
  51477. for (var index = 0; index < runtimeAnimations.length; index++) {
  51478. runtimeAnimations[index].goToFrame(frame);
  51479. }
  51480. };
  51481. /**
  51482. * Pause the animation
  51483. */
  51484. Animatable.prototype.pause = function () {
  51485. if (this._paused) {
  51486. return;
  51487. }
  51488. this._paused = true;
  51489. };
  51490. /**
  51491. * Restart the animation
  51492. */
  51493. Animatable.prototype.restart = function () {
  51494. this._paused = false;
  51495. };
  51496. Animatable.prototype._raiseOnAnimationEnd = function () {
  51497. if (this.onAnimationEnd) {
  51498. this.onAnimationEnd();
  51499. }
  51500. this.onAnimationEndObservable.notifyObservers(this);
  51501. };
  51502. /**
  51503. * Stop and delete the current animation
  51504. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51505. */
  51506. Animatable.prototype.stop = function (animationName) {
  51507. if (animationName) {
  51508. var idx = this._scene._activeAnimatables.indexOf(this);
  51509. if (idx > -1) {
  51510. var runtimeAnimations = this._runtimeAnimations;
  51511. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51512. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51513. continue;
  51514. }
  51515. runtimeAnimations[index].dispose();
  51516. runtimeAnimations.splice(index, 1);
  51517. }
  51518. if (runtimeAnimations.length == 0) {
  51519. this._scene._activeAnimatables.splice(idx, 1);
  51520. this._raiseOnAnimationEnd();
  51521. }
  51522. }
  51523. }
  51524. else {
  51525. var index = this._scene._activeAnimatables.indexOf(this);
  51526. if (index > -1) {
  51527. this._scene._activeAnimatables.splice(index, 1);
  51528. var runtimeAnimations = this._runtimeAnimations;
  51529. for (var index = 0; index < runtimeAnimations.length; index++) {
  51530. runtimeAnimations[index].dispose();
  51531. }
  51532. this._raiseOnAnimationEnd();
  51533. }
  51534. }
  51535. };
  51536. /**
  51537. * Wait asynchronously for the animation to end
  51538. * @returns a promise which will be fullfilled when the animation ends
  51539. */
  51540. Animatable.prototype.waitAsync = function () {
  51541. var _this = this;
  51542. return new Promise(function (resolve, reject) {
  51543. _this.onAnimationEndObservable.add(function () {
  51544. resolve(_this);
  51545. }, undefined, undefined, _this, true);
  51546. });
  51547. };
  51548. /** @hidden */
  51549. Animatable.prototype._animate = function (delay) {
  51550. if (this._paused) {
  51551. this.animationStarted = false;
  51552. if (this._pausedDelay === null) {
  51553. this._pausedDelay = delay;
  51554. }
  51555. return true;
  51556. }
  51557. if (this._localDelayOffset === null) {
  51558. this._localDelayOffset = delay;
  51559. this._pausedDelay = null;
  51560. }
  51561. else if (this._pausedDelay !== null) {
  51562. this._localDelayOffset += delay - this._pausedDelay;
  51563. this._pausedDelay = null;
  51564. }
  51565. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51566. return true;
  51567. }
  51568. // Animating
  51569. var running = false;
  51570. var runtimeAnimations = this._runtimeAnimations;
  51571. var index;
  51572. for (index = 0; index < runtimeAnimations.length; index++) {
  51573. var animation = runtimeAnimations[index];
  51574. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51575. running = running || isRunning;
  51576. }
  51577. this.animationStarted = running;
  51578. if (!running) {
  51579. if (this.disposeOnEnd) {
  51580. // Remove from active animatables
  51581. index = this._scene._activeAnimatables.indexOf(this);
  51582. this._scene._activeAnimatables.splice(index, 1);
  51583. // Dispose all runtime animations
  51584. for (index = 0; index < runtimeAnimations.length; index++) {
  51585. runtimeAnimations[index].dispose();
  51586. }
  51587. }
  51588. this._raiseOnAnimationEnd();
  51589. if (this.disposeOnEnd) {
  51590. this.onAnimationEnd = null;
  51591. this.onAnimationEndObservable.clear();
  51592. }
  51593. }
  51594. return running;
  51595. };
  51596. return Animatable;
  51597. }());
  51598. BABYLON.Animatable = Animatable;
  51599. })(BABYLON || (BABYLON = {}));
  51600. //# sourceMappingURL=babylon.animatable.js.map
  51601. var BABYLON;
  51602. (function (BABYLON) {
  51603. var EasingFunction = /** @class */ (function () {
  51604. function EasingFunction() {
  51605. // Properties
  51606. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51607. }
  51608. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51609. get: function () {
  51610. return EasingFunction._EASINGMODE_EASEIN;
  51611. },
  51612. enumerable: true,
  51613. configurable: true
  51614. });
  51615. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51616. get: function () {
  51617. return EasingFunction._EASINGMODE_EASEOUT;
  51618. },
  51619. enumerable: true,
  51620. configurable: true
  51621. });
  51622. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51623. get: function () {
  51624. return EasingFunction._EASINGMODE_EASEINOUT;
  51625. },
  51626. enumerable: true,
  51627. configurable: true
  51628. });
  51629. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51630. var n = Math.min(Math.max(easingMode, 0), 2);
  51631. this._easingMode = n;
  51632. };
  51633. EasingFunction.prototype.getEasingMode = function () {
  51634. return this._easingMode;
  51635. };
  51636. EasingFunction.prototype.easeInCore = function (gradient) {
  51637. throw new Error('You must implement this method');
  51638. };
  51639. EasingFunction.prototype.ease = function (gradient) {
  51640. switch (this._easingMode) {
  51641. case EasingFunction.EASINGMODE_EASEIN:
  51642. return this.easeInCore(gradient);
  51643. case EasingFunction.EASINGMODE_EASEOUT:
  51644. return (1 - this.easeInCore(1 - gradient));
  51645. }
  51646. if (gradient >= 0.5) {
  51647. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51648. }
  51649. return (this.easeInCore(gradient * 2) * 0.5);
  51650. };
  51651. //Statics
  51652. EasingFunction._EASINGMODE_EASEIN = 0;
  51653. EasingFunction._EASINGMODE_EASEOUT = 1;
  51654. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51655. return EasingFunction;
  51656. }());
  51657. BABYLON.EasingFunction = EasingFunction;
  51658. var CircleEase = /** @class */ (function (_super) {
  51659. __extends(CircleEase, _super);
  51660. function CircleEase() {
  51661. return _super !== null && _super.apply(this, arguments) || this;
  51662. }
  51663. CircleEase.prototype.easeInCore = function (gradient) {
  51664. gradient = Math.max(0, Math.min(1, gradient));
  51665. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51666. };
  51667. return CircleEase;
  51668. }(EasingFunction));
  51669. BABYLON.CircleEase = CircleEase;
  51670. var BackEase = /** @class */ (function (_super) {
  51671. __extends(BackEase, _super);
  51672. function BackEase(amplitude) {
  51673. if (amplitude === void 0) { amplitude = 1; }
  51674. var _this = _super.call(this) || this;
  51675. _this.amplitude = amplitude;
  51676. return _this;
  51677. }
  51678. BackEase.prototype.easeInCore = function (gradient) {
  51679. var num = Math.max(0, this.amplitude);
  51680. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51681. };
  51682. return BackEase;
  51683. }(EasingFunction));
  51684. BABYLON.BackEase = BackEase;
  51685. var BounceEase = /** @class */ (function (_super) {
  51686. __extends(BounceEase, _super);
  51687. function BounceEase(bounces, bounciness) {
  51688. if (bounces === void 0) { bounces = 3; }
  51689. if (bounciness === void 0) { bounciness = 2; }
  51690. var _this = _super.call(this) || this;
  51691. _this.bounces = bounces;
  51692. _this.bounciness = bounciness;
  51693. return _this;
  51694. }
  51695. BounceEase.prototype.easeInCore = function (gradient) {
  51696. var y = Math.max(0.0, this.bounces);
  51697. var bounciness = this.bounciness;
  51698. if (bounciness <= 1.0) {
  51699. bounciness = 1.001;
  51700. }
  51701. var num9 = Math.pow(bounciness, y);
  51702. var num5 = 1.0 - bounciness;
  51703. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51704. var num15 = gradient * num4;
  51705. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51706. var num3 = Math.floor(num65);
  51707. var num13 = num3 + 1.0;
  51708. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51709. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51710. var num7 = (num8 + num12) * 0.5;
  51711. var num6 = gradient - num7;
  51712. var num2 = num7 - num8;
  51713. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51714. };
  51715. return BounceEase;
  51716. }(EasingFunction));
  51717. BABYLON.BounceEase = BounceEase;
  51718. var CubicEase = /** @class */ (function (_super) {
  51719. __extends(CubicEase, _super);
  51720. function CubicEase() {
  51721. return _super !== null && _super.apply(this, arguments) || this;
  51722. }
  51723. CubicEase.prototype.easeInCore = function (gradient) {
  51724. return (gradient * gradient * gradient);
  51725. };
  51726. return CubicEase;
  51727. }(EasingFunction));
  51728. BABYLON.CubicEase = CubicEase;
  51729. var ElasticEase = /** @class */ (function (_super) {
  51730. __extends(ElasticEase, _super);
  51731. function ElasticEase(oscillations, springiness) {
  51732. if (oscillations === void 0) { oscillations = 3; }
  51733. if (springiness === void 0) { springiness = 3; }
  51734. var _this = _super.call(this) || this;
  51735. _this.oscillations = oscillations;
  51736. _this.springiness = springiness;
  51737. return _this;
  51738. }
  51739. ElasticEase.prototype.easeInCore = function (gradient) {
  51740. var num2;
  51741. var num3 = Math.max(0.0, this.oscillations);
  51742. var num = Math.max(0.0, this.springiness);
  51743. if (num == 0) {
  51744. num2 = gradient;
  51745. }
  51746. else {
  51747. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51748. }
  51749. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51750. };
  51751. return ElasticEase;
  51752. }(EasingFunction));
  51753. BABYLON.ElasticEase = ElasticEase;
  51754. var ExponentialEase = /** @class */ (function (_super) {
  51755. __extends(ExponentialEase, _super);
  51756. function ExponentialEase(exponent) {
  51757. if (exponent === void 0) { exponent = 2; }
  51758. var _this = _super.call(this) || this;
  51759. _this.exponent = exponent;
  51760. return _this;
  51761. }
  51762. ExponentialEase.prototype.easeInCore = function (gradient) {
  51763. if (this.exponent <= 0) {
  51764. return gradient;
  51765. }
  51766. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51767. };
  51768. return ExponentialEase;
  51769. }(EasingFunction));
  51770. BABYLON.ExponentialEase = ExponentialEase;
  51771. var PowerEase = /** @class */ (function (_super) {
  51772. __extends(PowerEase, _super);
  51773. function PowerEase(power) {
  51774. if (power === void 0) { power = 2; }
  51775. var _this = _super.call(this) || this;
  51776. _this.power = power;
  51777. return _this;
  51778. }
  51779. PowerEase.prototype.easeInCore = function (gradient) {
  51780. var y = Math.max(0.0, this.power);
  51781. return Math.pow(gradient, y);
  51782. };
  51783. return PowerEase;
  51784. }(EasingFunction));
  51785. BABYLON.PowerEase = PowerEase;
  51786. var QuadraticEase = /** @class */ (function (_super) {
  51787. __extends(QuadraticEase, _super);
  51788. function QuadraticEase() {
  51789. return _super !== null && _super.apply(this, arguments) || this;
  51790. }
  51791. QuadraticEase.prototype.easeInCore = function (gradient) {
  51792. return (gradient * gradient);
  51793. };
  51794. return QuadraticEase;
  51795. }(EasingFunction));
  51796. BABYLON.QuadraticEase = QuadraticEase;
  51797. var QuarticEase = /** @class */ (function (_super) {
  51798. __extends(QuarticEase, _super);
  51799. function QuarticEase() {
  51800. return _super !== null && _super.apply(this, arguments) || this;
  51801. }
  51802. QuarticEase.prototype.easeInCore = function (gradient) {
  51803. return (gradient * gradient * gradient * gradient);
  51804. };
  51805. return QuarticEase;
  51806. }(EasingFunction));
  51807. BABYLON.QuarticEase = QuarticEase;
  51808. var QuinticEase = /** @class */ (function (_super) {
  51809. __extends(QuinticEase, _super);
  51810. function QuinticEase() {
  51811. return _super !== null && _super.apply(this, arguments) || this;
  51812. }
  51813. QuinticEase.prototype.easeInCore = function (gradient) {
  51814. return (gradient * gradient * gradient * gradient * gradient);
  51815. };
  51816. return QuinticEase;
  51817. }(EasingFunction));
  51818. BABYLON.QuinticEase = QuinticEase;
  51819. var SineEase = /** @class */ (function (_super) {
  51820. __extends(SineEase, _super);
  51821. function SineEase() {
  51822. return _super !== null && _super.apply(this, arguments) || this;
  51823. }
  51824. SineEase.prototype.easeInCore = function (gradient) {
  51825. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51826. };
  51827. return SineEase;
  51828. }(EasingFunction));
  51829. BABYLON.SineEase = SineEase;
  51830. var BezierCurveEase = /** @class */ (function (_super) {
  51831. __extends(BezierCurveEase, _super);
  51832. function BezierCurveEase(x1, y1, x2, y2) {
  51833. if (x1 === void 0) { x1 = 0; }
  51834. if (y1 === void 0) { y1 = 0; }
  51835. if (x2 === void 0) { x2 = 1; }
  51836. if (y2 === void 0) { y2 = 1; }
  51837. var _this = _super.call(this) || this;
  51838. _this.x1 = x1;
  51839. _this.y1 = y1;
  51840. _this.x2 = x2;
  51841. _this.y2 = y2;
  51842. return _this;
  51843. }
  51844. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51845. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51846. };
  51847. return BezierCurveEase;
  51848. }(EasingFunction));
  51849. BABYLON.BezierCurveEase = BezierCurveEase;
  51850. })(BABYLON || (BABYLON = {}));
  51851. //# sourceMappingURL=babylon.easing.js.map
  51852. var BABYLON;
  51853. (function (BABYLON) {
  51854. /**
  51855. * A Condition applied to an Action
  51856. */
  51857. var Condition = /** @class */ (function () {
  51858. /**
  51859. * Creates a new Condition
  51860. * @param actionManager the manager of the action the condition is applied to
  51861. */
  51862. function Condition(actionManager) {
  51863. this._actionManager = actionManager;
  51864. }
  51865. /**
  51866. * Check if the current condition is valid
  51867. * @returns a boolean
  51868. */
  51869. Condition.prototype.isValid = function () {
  51870. return true;
  51871. };
  51872. /**
  51873. * Internal only
  51874. * @hidden
  51875. */
  51876. Condition.prototype._getProperty = function (propertyPath) {
  51877. return this._actionManager._getProperty(propertyPath);
  51878. };
  51879. /**
  51880. * Internal only
  51881. * @hidden
  51882. */
  51883. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51884. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51885. };
  51886. /**
  51887. * Serialize placeholder for child classes
  51888. * @returns the serialized object
  51889. */
  51890. Condition.prototype.serialize = function () {
  51891. };
  51892. /**
  51893. * Internal only
  51894. * @hidden
  51895. */
  51896. Condition.prototype._serialize = function (serializedCondition) {
  51897. return {
  51898. type: 2,
  51899. children: [],
  51900. name: serializedCondition.name,
  51901. properties: serializedCondition.properties
  51902. };
  51903. };
  51904. return Condition;
  51905. }());
  51906. BABYLON.Condition = Condition;
  51907. /**
  51908. * Defines specific conditional operators as extensions of Condition
  51909. */
  51910. var ValueCondition = /** @class */ (function (_super) {
  51911. __extends(ValueCondition, _super);
  51912. /**
  51913. * Creates a new ValueCondition
  51914. * @param actionManager manager for the action the condition applies to
  51915. * @param target for the action
  51916. * @param propertyPath path to specify the property of the target the conditional operator uses
  51917. * @param value the value compared by the conditional operator against the current value of the property
  51918. * @param operator the conditional operator, default ValueCondition.IsEqual
  51919. */
  51920. function ValueCondition(actionManager, target,
  51921. /** path to specify the property of the target the conditional operator uses */
  51922. propertyPath,
  51923. /** the value compared by the conditional operator against the current value of the property */
  51924. value,
  51925. /** the conditional operator, default ValueCondition.IsEqual */
  51926. operator) {
  51927. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51928. var _this = _super.call(this, actionManager) || this;
  51929. _this.propertyPath = propertyPath;
  51930. _this.value = value;
  51931. _this.operator = operator;
  51932. _this._target = target;
  51933. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51934. _this._property = _this._getProperty(_this.propertyPath);
  51935. return _this;
  51936. }
  51937. Object.defineProperty(ValueCondition, "IsEqual", {
  51938. /**
  51939. * returns the number for IsEqual
  51940. */
  51941. get: function () {
  51942. return ValueCondition._IsEqual;
  51943. },
  51944. enumerable: true,
  51945. configurable: true
  51946. });
  51947. Object.defineProperty(ValueCondition, "IsDifferent", {
  51948. /**
  51949. * Returns the number for IsDifferent
  51950. */
  51951. get: function () {
  51952. return ValueCondition._IsDifferent;
  51953. },
  51954. enumerable: true,
  51955. configurable: true
  51956. });
  51957. Object.defineProperty(ValueCondition, "IsGreater", {
  51958. /**
  51959. * Returns the number for IsGreater
  51960. */
  51961. get: function () {
  51962. return ValueCondition._IsGreater;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(ValueCondition, "IsLesser", {
  51968. /**
  51969. * Returns the number for IsLesser
  51970. */
  51971. get: function () {
  51972. return ValueCondition._IsLesser;
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. /**
  51978. * Compares the given value with the property value for the specified conditional operator
  51979. * @returns the result of the comparison
  51980. */
  51981. ValueCondition.prototype.isValid = function () {
  51982. switch (this.operator) {
  51983. case ValueCondition.IsGreater:
  51984. return this._effectiveTarget[this._property] > this.value;
  51985. case ValueCondition.IsLesser:
  51986. return this._effectiveTarget[this._property] < this.value;
  51987. case ValueCondition.IsEqual:
  51988. case ValueCondition.IsDifferent:
  51989. var check;
  51990. if (this.value.equals) {
  51991. check = this.value.equals(this._effectiveTarget[this._property]);
  51992. }
  51993. else {
  51994. check = this.value === this._effectiveTarget[this._property];
  51995. }
  51996. return this.operator === ValueCondition.IsEqual ? check : !check;
  51997. }
  51998. return false;
  51999. };
  52000. /**
  52001. * Serialize the ValueCondition into a JSON compatible object
  52002. * @returns serialization object
  52003. */
  52004. ValueCondition.prototype.serialize = function () {
  52005. return this._serialize({
  52006. name: "ValueCondition",
  52007. properties: [
  52008. BABYLON.Action._GetTargetProperty(this._target),
  52009. { name: "propertyPath", value: this.propertyPath },
  52010. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52011. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52012. ]
  52013. });
  52014. };
  52015. /**
  52016. * Gets the name of the conditional operator for the ValueCondition
  52017. * @param operator the conditional operator
  52018. * @returns the name
  52019. */
  52020. ValueCondition.GetOperatorName = function (operator) {
  52021. switch (operator) {
  52022. case ValueCondition._IsEqual: return "IsEqual";
  52023. case ValueCondition._IsDifferent: return "IsDifferent";
  52024. case ValueCondition._IsGreater: return "IsGreater";
  52025. case ValueCondition._IsLesser: return "IsLesser";
  52026. default: return "";
  52027. }
  52028. };
  52029. /**
  52030. * Internal only
  52031. * @hidden
  52032. */
  52033. ValueCondition._IsEqual = 0;
  52034. /**
  52035. * Internal only
  52036. * @hidden
  52037. */
  52038. ValueCondition._IsDifferent = 1;
  52039. /**
  52040. * Internal only
  52041. * @hidden
  52042. */
  52043. ValueCondition._IsGreater = 2;
  52044. /**
  52045. * Internal only
  52046. * @hidden
  52047. */
  52048. ValueCondition._IsLesser = 3;
  52049. return ValueCondition;
  52050. }(Condition));
  52051. BABYLON.ValueCondition = ValueCondition;
  52052. /**
  52053. * Defines a predicate condition as an extension of Condition
  52054. */
  52055. var PredicateCondition = /** @class */ (function (_super) {
  52056. __extends(PredicateCondition, _super);
  52057. /**
  52058. * Creates a new PredicateCondition
  52059. * @param actionManager manager for the action the condition applies to
  52060. * @param predicate defines the predicate function used to validate the condition
  52061. */
  52062. function PredicateCondition(actionManager,
  52063. /** defines the predicate function used to validate the condition */
  52064. predicate) {
  52065. var _this = _super.call(this, actionManager) || this;
  52066. _this.predicate = predicate;
  52067. return _this;
  52068. }
  52069. /**
  52070. * @returns the validity of the predicate condition
  52071. */
  52072. PredicateCondition.prototype.isValid = function () {
  52073. return this.predicate();
  52074. };
  52075. return PredicateCondition;
  52076. }(Condition));
  52077. BABYLON.PredicateCondition = PredicateCondition;
  52078. /**
  52079. * Defines a state condition as an extension of Condition
  52080. */
  52081. var StateCondition = /** @class */ (function (_super) {
  52082. __extends(StateCondition, _super);
  52083. /**
  52084. * Creates a new StateCondition
  52085. * @param actionManager manager for the action the condition applies to
  52086. * @param target of the condition
  52087. * @param value to compare with target state
  52088. */
  52089. function StateCondition(actionManager, target, value) {
  52090. var _this = _super.call(this, actionManager) || this;
  52091. _this.value = value;
  52092. _this._target = target;
  52093. return _this;
  52094. }
  52095. /**
  52096. * @returns the validity of the state
  52097. */
  52098. StateCondition.prototype.isValid = function () {
  52099. return this._target.state === this.value;
  52100. };
  52101. /**
  52102. * Serialize the StateCondition into a JSON compatible object
  52103. * @returns serialization object
  52104. */
  52105. StateCondition.prototype.serialize = function () {
  52106. return this._serialize({
  52107. name: "StateCondition",
  52108. properties: [
  52109. BABYLON.Action._GetTargetProperty(this._target),
  52110. { name: "value", value: this.value }
  52111. ]
  52112. });
  52113. };
  52114. return StateCondition;
  52115. }(Condition));
  52116. BABYLON.StateCondition = StateCondition;
  52117. })(BABYLON || (BABYLON = {}));
  52118. //# sourceMappingURL=babylon.condition.js.map
  52119. var BABYLON;
  52120. (function (BABYLON) {
  52121. /**
  52122. * The action to be carried out following a trigger
  52123. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52124. */
  52125. var Action = /** @class */ (function () {
  52126. /**
  52127. * Creates a new Action
  52128. * @param triggerOptions the trigger, with or without parameters, for the action
  52129. * @param condition an optional determinant of action
  52130. */
  52131. function Action(
  52132. /** the trigger, with or without parameters, for the action */
  52133. triggerOptions, condition) {
  52134. this.triggerOptions = triggerOptions;
  52135. /**
  52136. * An event triggered prior to action being executed.
  52137. */
  52138. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52139. if (triggerOptions.parameter) {
  52140. this.trigger = triggerOptions.trigger;
  52141. this._triggerParameter = triggerOptions.parameter;
  52142. }
  52143. else {
  52144. this.trigger = triggerOptions;
  52145. }
  52146. this._nextActiveAction = this;
  52147. this._condition = condition;
  52148. }
  52149. /**
  52150. * Internal only
  52151. * @hidden
  52152. */
  52153. Action.prototype._prepare = function () {
  52154. };
  52155. /**
  52156. * Gets the trigger parameters
  52157. * @returns the trigger parameters
  52158. */
  52159. Action.prototype.getTriggerParameter = function () {
  52160. return this._triggerParameter;
  52161. };
  52162. /**
  52163. * Internal only - executes current action event
  52164. * @hidden
  52165. */
  52166. Action.prototype._executeCurrent = function (evt) {
  52167. if (this._nextActiveAction._condition) {
  52168. var condition = this._nextActiveAction._condition;
  52169. var currentRenderId = this._actionManager.getScene().getRenderId();
  52170. // We cache the current evaluation for the current frame
  52171. if (condition._evaluationId === currentRenderId) {
  52172. if (!condition._currentResult) {
  52173. return;
  52174. }
  52175. }
  52176. else {
  52177. condition._evaluationId = currentRenderId;
  52178. if (!condition.isValid()) {
  52179. condition._currentResult = false;
  52180. return;
  52181. }
  52182. condition._currentResult = true;
  52183. }
  52184. }
  52185. this.onBeforeExecuteObservable.notifyObservers(this);
  52186. this._nextActiveAction.execute(evt);
  52187. this.skipToNextActiveAction();
  52188. };
  52189. /**
  52190. * Execute placeholder for child classes
  52191. * @param evt optional action event
  52192. */
  52193. Action.prototype.execute = function (evt) {
  52194. };
  52195. /**
  52196. * Skips to next active action
  52197. */
  52198. Action.prototype.skipToNextActiveAction = function () {
  52199. if (this._nextActiveAction._child) {
  52200. if (!this._nextActiveAction._child._actionManager) {
  52201. this._nextActiveAction._child._actionManager = this._actionManager;
  52202. }
  52203. this._nextActiveAction = this._nextActiveAction._child;
  52204. }
  52205. else {
  52206. this._nextActiveAction = this;
  52207. }
  52208. };
  52209. /**
  52210. * Adds action to chain of actions, may be a DoNothingAction
  52211. * @param action defines the next action to execute
  52212. * @returns The action passed in
  52213. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52214. */
  52215. Action.prototype.then = function (action) {
  52216. this._child = action;
  52217. action._actionManager = this._actionManager;
  52218. action._prepare();
  52219. return action;
  52220. };
  52221. /**
  52222. * Internal only
  52223. * @hidden
  52224. */
  52225. Action.prototype._getProperty = function (propertyPath) {
  52226. return this._actionManager._getProperty(propertyPath);
  52227. };
  52228. /**
  52229. * Internal only
  52230. * @hidden
  52231. */
  52232. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52233. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52234. };
  52235. /**
  52236. * Serialize placeholder for child classes
  52237. * @param parent of child
  52238. * @returns the serialized object
  52239. */
  52240. Action.prototype.serialize = function (parent) {
  52241. };
  52242. /**
  52243. * Internal only called by serialize
  52244. * @hidden
  52245. */
  52246. Action.prototype._serialize = function (serializedAction, parent) {
  52247. var serializationObject = {
  52248. type: 1,
  52249. children: [],
  52250. name: serializedAction.name,
  52251. properties: serializedAction.properties || []
  52252. };
  52253. // Serialize child
  52254. if (this._child) {
  52255. this._child.serialize(serializationObject);
  52256. }
  52257. // Check if "this" has a condition
  52258. if (this._condition) {
  52259. var serializedCondition = this._condition.serialize();
  52260. serializedCondition.children.push(serializationObject);
  52261. if (parent) {
  52262. parent.children.push(serializedCondition);
  52263. }
  52264. return serializedCondition;
  52265. }
  52266. if (parent) {
  52267. parent.children.push(serializationObject);
  52268. }
  52269. return serializationObject;
  52270. };
  52271. /**
  52272. * Internal only
  52273. * @hidden
  52274. */
  52275. Action._SerializeValueAsString = function (value) {
  52276. if (typeof value === "number") {
  52277. return value.toString();
  52278. }
  52279. if (typeof value === "boolean") {
  52280. return value ? "true" : "false";
  52281. }
  52282. if (value instanceof BABYLON.Vector2) {
  52283. return value.x + ", " + value.y;
  52284. }
  52285. if (value instanceof BABYLON.Vector3) {
  52286. return value.x + ", " + value.y + ", " + value.z;
  52287. }
  52288. if (value instanceof BABYLON.Color3) {
  52289. return value.r + ", " + value.g + ", " + value.b;
  52290. }
  52291. if (value instanceof BABYLON.Color4) {
  52292. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52293. }
  52294. return value; // string
  52295. };
  52296. /**
  52297. * Internal only
  52298. * @hidden
  52299. */
  52300. Action._GetTargetProperty = function (target) {
  52301. return {
  52302. name: "target",
  52303. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52304. : target instanceof BABYLON.Light ? "LightProperties"
  52305. : target instanceof BABYLON.Camera ? "CameraProperties"
  52306. : "SceneProperties",
  52307. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52308. };
  52309. };
  52310. return Action;
  52311. }());
  52312. BABYLON.Action = Action;
  52313. })(BABYLON || (BABYLON = {}));
  52314. //# sourceMappingURL=babylon.action.js.map
  52315. var BABYLON;
  52316. (function (BABYLON) {
  52317. /**
  52318. * ActionEvent is the event being sent when an action is triggered.
  52319. */
  52320. var ActionEvent = /** @class */ (function () {
  52321. /**
  52322. * Creates a new ActionEvent
  52323. * @param source The mesh or sprite that triggered the action
  52324. * @param pointerX The X mouse cursor position at the time of the event
  52325. * @param pointerY The Y mouse cursor position at the time of the event
  52326. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52327. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52328. * @param additionalData additional data for the event
  52329. */
  52330. function ActionEvent(
  52331. /** The mesh or sprite that triggered the action */
  52332. source,
  52333. /** The X mouse cursor position at the time of the event */
  52334. pointerX,
  52335. /** The Y mouse cursor position at the time of the event */
  52336. pointerY,
  52337. /** The mesh that is currently pointed at (can be null) */
  52338. meshUnderPointer,
  52339. /** the original (browser) event that triggered the ActionEvent */
  52340. sourceEvent,
  52341. /** additional data for the event */
  52342. additionalData) {
  52343. this.source = source;
  52344. this.pointerX = pointerX;
  52345. this.pointerY = pointerY;
  52346. this.meshUnderPointer = meshUnderPointer;
  52347. this.sourceEvent = sourceEvent;
  52348. this.additionalData = additionalData;
  52349. }
  52350. /**
  52351. * Helper function to auto-create an ActionEvent from a source mesh.
  52352. * @param source The source mesh that triggered the event
  52353. * @param evt The original (browser) event
  52354. * @param additionalData additional data for the event
  52355. * @returns the new ActionEvent
  52356. */
  52357. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52358. var scene = source.getScene();
  52359. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52360. };
  52361. /**
  52362. * Helper function to auto-create an ActionEvent from a source sprite
  52363. * @param source The source sprite that triggered the event
  52364. * @param scene Scene associated with the sprite
  52365. * @param evt The original (browser) event
  52366. * @param additionalData additional data for the event
  52367. * @returns the new ActionEvent
  52368. */
  52369. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52370. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52371. };
  52372. /**
  52373. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52374. * @param scene the scene where the event occurred
  52375. * @param evt The original (browser) event
  52376. * @returns the new ActionEvent
  52377. */
  52378. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52379. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52380. };
  52381. /**
  52382. * Helper function to auto-create an ActionEvent from a primitive
  52383. * @param prim defines the target primitive
  52384. * @param pointerPos defines the pointer position
  52385. * @param evt The original (browser) event
  52386. * @param additionalData additional data for the event
  52387. * @returns the new ActionEvent
  52388. */
  52389. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52390. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52391. };
  52392. return ActionEvent;
  52393. }());
  52394. BABYLON.ActionEvent = ActionEvent;
  52395. /**
  52396. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52397. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52398. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52399. */
  52400. var ActionManager = /** @class */ (function () {
  52401. /**
  52402. * Creates a new action manager
  52403. * @param scene defines the hosting scene
  52404. */
  52405. function ActionManager(scene) {
  52406. // Members
  52407. /** Gets the list of actions */
  52408. this.actions = new Array();
  52409. /** Gets the cursor to use when hovering items */
  52410. this.hoverCursor = '';
  52411. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52412. scene.actionManagers.push(this);
  52413. }
  52414. Object.defineProperty(ActionManager, "NothingTrigger", {
  52415. /**
  52416. * Nothing
  52417. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52418. */
  52419. get: function () {
  52420. return ActionManager._NothingTrigger;
  52421. },
  52422. enumerable: true,
  52423. configurable: true
  52424. });
  52425. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52426. /**
  52427. * On pick
  52428. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52429. */
  52430. get: function () {
  52431. return ActionManager._OnPickTrigger;
  52432. },
  52433. enumerable: true,
  52434. configurable: true
  52435. });
  52436. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52437. /**
  52438. * On left pick
  52439. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52440. */
  52441. get: function () {
  52442. return ActionManager._OnLeftPickTrigger;
  52443. },
  52444. enumerable: true,
  52445. configurable: true
  52446. });
  52447. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52448. /**
  52449. * On right pick
  52450. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52451. */
  52452. get: function () {
  52453. return ActionManager._OnRightPickTrigger;
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52459. /**
  52460. * On center pick
  52461. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52462. */
  52463. get: function () {
  52464. return ActionManager._OnCenterPickTrigger;
  52465. },
  52466. enumerable: true,
  52467. configurable: true
  52468. });
  52469. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52470. /**
  52471. * On pick down
  52472. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52473. */
  52474. get: function () {
  52475. return ActionManager._OnPickDownTrigger;
  52476. },
  52477. enumerable: true,
  52478. configurable: true
  52479. });
  52480. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52481. /**
  52482. * On double pick
  52483. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52484. */
  52485. get: function () {
  52486. return ActionManager._OnDoublePickTrigger;
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52492. /**
  52493. * On pick up
  52494. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52495. */
  52496. get: function () {
  52497. return ActionManager._OnPickUpTrigger;
  52498. },
  52499. enumerable: true,
  52500. configurable: true
  52501. });
  52502. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52503. /**
  52504. * On pick out.
  52505. * This trigger will only be raised if you also declared a OnPickDown
  52506. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52507. */
  52508. get: function () {
  52509. return ActionManager._OnPickOutTrigger;
  52510. },
  52511. enumerable: true,
  52512. configurable: true
  52513. });
  52514. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52515. /**
  52516. * On long press
  52517. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52518. */
  52519. get: function () {
  52520. return ActionManager._OnLongPressTrigger;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52526. /**
  52527. * On pointer over
  52528. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52529. */
  52530. get: function () {
  52531. return ActionManager._OnPointerOverTrigger;
  52532. },
  52533. enumerable: true,
  52534. configurable: true
  52535. });
  52536. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52537. /**
  52538. * On pointer out
  52539. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52540. */
  52541. get: function () {
  52542. return ActionManager._OnPointerOutTrigger;
  52543. },
  52544. enumerable: true,
  52545. configurable: true
  52546. });
  52547. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52548. /**
  52549. * On every frame
  52550. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52551. */
  52552. get: function () {
  52553. return ActionManager._OnEveryFrameTrigger;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52559. /**
  52560. * On intersection enter
  52561. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52562. */
  52563. get: function () {
  52564. return ActionManager._OnIntersectionEnterTrigger;
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52570. /**
  52571. * On intersection exit
  52572. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52573. */
  52574. get: function () {
  52575. return ActionManager._OnIntersectionExitTrigger;
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52581. /**
  52582. * On key down
  52583. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52584. */
  52585. get: function () {
  52586. return ActionManager._OnKeyDownTrigger;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52592. /**
  52593. * On key up
  52594. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52595. */
  52596. get: function () {
  52597. return ActionManager._OnKeyUpTrigger;
  52598. },
  52599. enumerable: true,
  52600. configurable: true
  52601. });
  52602. // Methods
  52603. /**
  52604. * Releases all associated resources
  52605. */
  52606. ActionManager.prototype.dispose = function () {
  52607. var index = this._scene.actionManagers.indexOf(this);
  52608. for (var i = 0; i < this.actions.length; i++) {
  52609. var action = this.actions[i];
  52610. ActionManager.Triggers[action.trigger]--;
  52611. if (ActionManager.Triggers[action.trigger] === 0) {
  52612. delete ActionManager.Triggers[action.trigger];
  52613. }
  52614. }
  52615. if (index > -1) {
  52616. this._scene.actionManagers.splice(index, 1);
  52617. }
  52618. };
  52619. /**
  52620. * Gets hosting scene
  52621. * @returns the hosting scene
  52622. */
  52623. ActionManager.prototype.getScene = function () {
  52624. return this._scene;
  52625. };
  52626. /**
  52627. * Does this action manager handles actions of any of the given triggers
  52628. * @param triggers defines the triggers to be tested
  52629. * @return a boolean indicating whether one (or more) of the triggers is handled
  52630. */
  52631. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52632. for (var index = 0; index < this.actions.length; index++) {
  52633. var action = this.actions[index];
  52634. if (triggers.indexOf(action.trigger) > -1) {
  52635. return true;
  52636. }
  52637. }
  52638. return false;
  52639. };
  52640. /**
  52641. * Does this action manager handles actions of a given trigger
  52642. * @param trigger defines the trigger to be tested
  52643. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52644. * @return whether the trigger is handled
  52645. */
  52646. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52647. for (var index = 0; index < this.actions.length; index++) {
  52648. var action = this.actions[index];
  52649. if (action.trigger === trigger) {
  52650. if (parameterPredicate) {
  52651. if (parameterPredicate(action.getTriggerParameter())) {
  52652. return true;
  52653. }
  52654. }
  52655. else {
  52656. return true;
  52657. }
  52658. }
  52659. }
  52660. return false;
  52661. };
  52662. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52663. /**
  52664. * Does this action manager has pointer triggers
  52665. */
  52666. get: function () {
  52667. for (var index = 0; index < this.actions.length; index++) {
  52668. var action = this.actions[index];
  52669. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52670. return true;
  52671. }
  52672. }
  52673. return false;
  52674. },
  52675. enumerable: true,
  52676. configurable: true
  52677. });
  52678. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52679. /**
  52680. * Does this action manager has pick triggers
  52681. */
  52682. get: function () {
  52683. for (var index = 0; index < this.actions.length; index++) {
  52684. var action = this.actions[index];
  52685. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52686. return true;
  52687. }
  52688. }
  52689. return false;
  52690. },
  52691. enumerable: true,
  52692. configurable: true
  52693. });
  52694. Object.defineProperty(ActionManager, "HasTriggers", {
  52695. /**
  52696. * Does exist one action manager with at least one trigger
  52697. **/
  52698. get: function () {
  52699. for (var t in ActionManager.Triggers) {
  52700. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52701. return true;
  52702. }
  52703. }
  52704. return false;
  52705. },
  52706. enumerable: true,
  52707. configurable: true
  52708. });
  52709. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52710. /**
  52711. * Does exist one action manager with at least one pick trigger
  52712. **/
  52713. get: function () {
  52714. for (var t in ActionManager.Triggers) {
  52715. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52716. var t_int = parseInt(t);
  52717. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52718. return true;
  52719. }
  52720. }
  52721. }
  52722. return false;
  52723. },
  52724. enumerable: true,
  52725. configurable: true
  52726. });
  52727. /**
  52728. * Does exist one action manager that handles actions of a given trigger
  52729. * @param trigger defines the trigger to be tested
  52730. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52731. **/
  52732. ActionManager.HasSpecificTrigger = function (trigger) {
  52733. for (var t in ActionManager.Triggers) {
  52734. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52735. var t_int = parseInt(t);
  52736. if (t_int === trigger) {
  52737. return true;
  52738. }
  52739. }
  52740. }
  52741. return false;
  52742. };
  52743. /**
  52744. * Registers an action to this action manager
  52745. * @param action defines the action to be registered
  52746. * @return the action amended (prepared) after registration
  52747. */
  52748. ActionManager.prototype.registerAction = function (action) {
  52749. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52750. if (this.getScene().actionManager !== this) {
  52751. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52752. return null;
  52753. }
  52754. }
  52755. this.actions.push(action);
  52756. if (ActionManager.Triggers[action.trigger]) {
  52757. ActionManager.Triggers[action.trigger]++;
  52758. }
  52759. else {
  52760. ActionManager.Triggers[action.trigger] = 1;
  52761. }
  52762. action._actionManager = this;
  52763. action._prepare();
  52764. return action;
  52765. };
  52766. /**
  52767. * Unregisters an action to this action manager
  52768. * @param action defines the action to be unregistered
  52769. * @return a boolean indicating whether the action has been unregistered
  52770. */
  52771. ActionManager.prototype.unregisterAction = function (action) {
  52772. var index = this.actions.indexOf(action);
  52773. if (index !== -1) {
  52774. this.actions.splice(index, 1);
  52775. ActionManager.Triggers[action.trigger] -= 1;
  52776. if (ActionManager.Triggers[action.trigger] === 0) {
  52777. delete ActionManager.Triggers[action.trigger];
  52778. }
  52779. delete action._actionManager;
  52780. return true;
  52781. }
  52782. return false;
  52783. };
  52784. /**
  52785. * Process a specific trigger
  52786. * @param trigger defines the trigger to process
  52787. * @param evt defines the event details to be processed
  52788. */
  52789. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52790. for (var index = 0; index < this.actions.length; index++) {
  52791. var action = this.actions[index];
  52792. if (action.trigger === trigger) {
  52793. if (evt) {
  52794. if (trigger === ActionManager.OnKeyUpTrigger
  52795. || trigger === ActionManager.OnKeyDownTrigger) {
  52796. var parameter = action.getTriggerParameter();
  52797. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52798. if (!parameter.toLowerCase) {
  52799. continue;
  52800. }
  52801. var lowerCase = parameter.toLowerCase();
  52802. if (lowerCase !== evt.sourceEvent.key) {
  52803. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52804. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52805. if (actualkey !== lowerCase) {
  52806. continue;
  52807. }
  52808. }
  52809. }
  52810. }
  52811. }
  52812. action._executeCurrent(evt);
  52813. }
  52814. }
  52815. };
  52816. /** @hidden */
  52817. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52818. var properties = propertyPath.split(".");
  52819. for (var index = 0; index < properties.length - 1; index++) {
  52820. target = target[properties[index]];
  52821. }
  52822. return target;
  52823. };
  52824. /** @hidden */
  52825. ActionManager.prototype._getProperty = function (propertyPath) {
  52826. var properties = propertyPath.split(".");
  52827. return properties[properties.length - 1];
  52828. };
  52829. /**
  52830. * Serialize this manager to a JSON object
  52831. * @param name defines the property name to store this manager
  52832. * @returns a JSON representation of this manager
  52833. */
  52834. ActionManager.prototype.serialize = function (name) {
  52835. var root = {
  52836. children: new Array(),
  52837. name: name,
  52838. type: 3,
  52839. properties: new Array() // Empty for root but required
  52840. };
  52841. for (var i = 0; i < this.actions.length; i++) {
  52842. var triggerObject = {
  52843. type: 0,
  52844. children: new Array(),
  52845. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52846. properties: new Array()
  52847. };
  52848. var triggerOptions = this.actions[i].triggerOptions;
  52849. if (triggerOptions && typeof triggerOptions !== "number") {
  52850. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52851. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52852. }
  52853. else {
  52854. var parameter = {};
  52855. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52856. if (triggerOptions.parameter.mesh) {
  52857. parameter._meshId = triggerOptions.parameter.mesh.id;
  52858. }
  52859. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52860. }
  52861. }
  52862. // Serialize child action, recursively
  52863. this.actions[i].serialize(triggerObject);
  52864. // Add serialized trigger
  52865. root.children.push(triggerObject);
  52866. }
  52867. return root;
  52868. };
  52869. /**
  52870. * Creates a new ActionManager from a JSON data
  52871. * @param parsedActions defines the JSON data to read from
  52872. * @param object defines the hosting mesh
  52873. * @param scene defines the hosting scene
  52874. */
  52875. ActionManager.Parse = function (parsedActions, object, scene) {
  52876. var actionManager = new ActionManager(scene);
  52877. if (object === null)
  52878. scene.actionManager = actionManager;
  52879. else
  52880. object.actionManager = actionManager;
  52881. // instanciate a new object
  52882. var instanciate = function (name, params) {
  52883. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52884. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52885. newInstance.constructor.apply(newInstance, params);
  52886. return newInstance;
  52887. };
  52888. var parseParameter = function (name, value, target, propertyPath) {
  52889. if (propertyPath === null) {
  52890. // String, boolean or float
  52891. var floatValue = parseFloat(value);
  52892. if (value === "true" || value === "false")
  52893. return value === "true";
  52894. else
  52895. return isNaN(floatValue) ? value : floatValue;
  52896. }
  52897. var effectiveTarget = propertyPath.split(".");
  52898. var values = value.split(",");
  52899. // Get effective Target
  52900. for (var i = 0; i < effectiveTarget.length; i++) {
  52901. target = target[effectiveTarget[i]];
  52902. }
  52903. // Return appropriate value with its type
  52904. if (typeof (target) === "boolean")
  52905. return values[0] === "true";
  52906. if (typeof (target) === "string")
  52907. return values[0];
  52908. // Parameters with multiple values such as Vector3 etc.
  52909. var split = new Array();
  52910. for (var i = 0; i < values.length; i++)
  52911. split.push(parseFloat(values[i]));
  52912. if (target instanceof BABYLON.Vector3)
  52913. return BABYLON.Vector3.FromArray(split);
  52914. if (target instanceof BABYLON.Vector4)
  52915. return BABYLON.Vector4.FromArray(split);
  52916. if (target instanceof BABYLON.Color3)
  52917. return BABYLON.Color3.FromArray(split);
  52918. if (target instanceof BABYLON.Color4)
  52919. return BABYLON.Color4.FromArray(split);
  52920. return parseFloat(values[0]);
  52921. };
  52922. // traverse graph per trigger
  52923. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52924. if (combineArray === void 0) { combineArray = null; }
  52925. if (parsedAction.detached)
  52926. return;
  52927. var parameters = new Array();
  52928. var target = null;
  52929. var propertyPath = null;
  52930. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52931. // Parameters
  52932. if (parsedAction.type === 2)
  52933. parameters.push(actionManager);
  52934. else
  52935. parameters.push(trigger);
  52936. if (combine) {
  52937. var actions = new Array();
  52938. for (var j = 0; j < parsedAction.combine.length; j++) {
  52939. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52940. }
  52941. parameters.push(actions);
  52942. }
  52943. else {
  52944. for (var i = 0; i < parsedAction.properties.length; i++) {
  52945. var value = parsedAction.properties[i].value;
  52946. var name = parsedAction.properties[i].name;
  52947. var targetType = parsedAction.properties[i].targetType;
  52948. if (name === "target")
  52949. if (targetType !== null && targetType === "SceneProperties")
  52950. value = target = scene;
  52951. else
  52952. value = target = scene.getNodeByName(value);
  52953. else if (name === "parent")
  52954. value = scene.getNodeByName(value);
  52955. else if (name === "sound")
  52956. value = scene.getSoundByName(value);
  52957. else if (name !== "propertyPath") {
  52958. if (parsedAction.type === 2 && name === "operator")
  52959. value = BABYLON.ValueCondition[value];
  52960. else
  52961. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52962. }
  52963. else {
  52964. propertyPath = value;
  52965. }
  52966. parameters.push(value);
  52967. }
  52968. }
  52969. if (combineArray === null) {
  52970. parameters.push(condition);
  52971. }
  52972. else {
  52973. parameters.push(null);
  52974. }
  52975. // If interpolate value action
  52976. if (parsedAction.name === "InterpolateValueAction") {
  52977. var param = parameters[parameters.length - 2];
  52978. parameters[parameters.length - 1] = param;
  52979. parameters[parameters.length - 2] = condition;
  52980. }
  52981. // Action or condition(s) and not CombineAction
  52982. var newAction = instanciate(parsedAction.name, parameters);
  52983. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52984. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52985. if (action)
  52986. action.then(nothing);
  52987. else
  52988. actionManager.registerAction(nothing);
  52989. action = nothing;
  52990. }
  52991. if (combineArray === null) {
  52992. if (newAction instanceof BABYLON.Condition) {
  52993. condition = newAction;
  52994. newAction = action;
  52995. }
  52996. else {
  52997. condition = null;
  52998. if (action)
  52999. action.then(newAction);
  53000. else
  53001. actionManager.registerAction(newAction);
  53002. }
  53003. }
  53004. else {
  53005. combineArray.push(newAction);
  53006. }
  53007. for (var i = 0; i < parsedAction.children.length; i++)
  53008. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53009. };
  53010. // triggers
  53011. for (var i = 0; i < parsedActions.children.length; i++) {
  53012. var triggerParams;
  53013. var trigger = parsedActions.children[i];
  53014. if (trigger.properties.length > 0) {
  53015. var param = trigger.properties[0].value;
  53016. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53017. if (value._meshId) {
  53018. value.mesh = scene.getMeshByID(value._meshId);
  53019. }
  53020. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53021. }
  53022. else
  53023. triggerParams = ActionManager[trigger.name];
  53024. for (var j = 0; j < trigger.children.length; j++) {
  53025. if (!trigger.detached)
  53026. traverse(trigger.children[j], triggerParams, null, null);
  53027. }
  53028. }
  53029. };
  53030. /**
  53031. * Get a trigger name by index
  53032. * @param trigger defines the trigger index
  53033. * @returns a trigger name
  53034. */
  53035. ActionManager.GetTriggerName = function (trigger) {
  53036. switch (trigger) {
  53037. case 0: return "NothingTrigger";
  53038. case 1: return "OnPickTrigger";
  53039. case 2: return "OnLeftPickTrigger";
  53040. case 3: return "OnRightPickTrigger";
  53041. case 4: return "OnCenterPickTrigger";
  53042. case 5: return "OnPickDownTrigger";
  53043. case 6: return "OnPickUpTrigger";
  53044. case 7: return "OnLongPressTrigger";
  53045. case 8: return "OnPointerOverTrigger";
  53046. case 9: return "OnPointerOutTrigger";
  53047. case 10: return "OnEveryFrameTrigger";
  53048. case 11: return "OnIntersectionEnterTrigger";
  53049. case 12: return "OnIntersectionExitTrigger";
  53050. case 13: return "OnKeyDownTrigger";
  53051. case 14: return "OnKeyUpTrigger";
  53052. case 15: return "OnPickOutTrigger";
  53053. default: return "";
  53054. }
  53055. };
  53056. // Statics
  53057. ActionManager._NothingTrigger = 0;
  53058. ActionManager._OnPickTrigger = 1;
  53059. ActionManager._OnLeftPickTrigger = 2;
  53060. ActionManager._OnRightPickTrigger = 3;
  53061. ActionManager._OnCenterPickTrigger = 4;
  53062. ActionManager._OnPickDownTrigger = 5;
  53063. ActionManager._OnDoublePickTrigger = 6;
  53064. ActionManager._OnPickUpTrigger = 7;
  53065. ActionManager._OnLongPressTrigger = 8;
  53066. ActionManager._OnPointerOverTrigger = 9;
  53067. ActionManager._OnPointerOutTrigger = 10;
  53068. ActionManager._OnEveryFrameTrigger = 11;
  53069. ActionManager._OnIntersectionEnterTrigger = 12;
  53070. ActionManager._OnIntersectionExitTrigger = 13;
  53071. ActionManager._OnKeyDownTrigger = 14;
  53072. ActionManager._OnKeyUpTrigger = 15;
  53073. ActionManager._OnPickOutTrigger = 16;
  53074. /** Gets the list of active triggers */
  53075. ActionManager.Triggers = {};
  53076. return ActionManager;
  53077. }());
  53078. BABYLON.ActionManager = ActionManager;
  53079. })(BABYLON || (BABYLON = {}));
  53080. //# sourceMappingURL=babylon.actionManager.js.map
  53081. var BABYLON;
  53082. (function (BABYLON) {
  53083. var InterpolateValueAction = /** @class */ (function (_super) {
  53084. __extends(InterpolateValueAction, _super);
  53085. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53086. if (duration === void 0) { duration = 1000; }
  53087. var _this = _super.call(this, triggerOptions, condition) || this;
  53088. _this.propertyPath = propertyPath;
  53089. _this.value = value;
  53090. _this.duration = duration;
  53091. _this.stopOtherAnimations = stopOtherAnimations;
  53092. _this.onInterpolationDone = onInterpolationDone;
  53093. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53094. _this._target = _this._effectiveTarget = target;
  53095. return _this;
  53096. }
  53097. InterpolateValueAction.prototype._prepare = function () {
  53098. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53099. this._property = this._getProperty(this.propertyPath);
  53100. };
  53101. InterpolateValueAction.prototype.execute = function () {
  53102. var _this = this;
  53103. var scene = this._actionManager.getScene();
  53104. var keys = [
  53105. {
  53106. frame: 0,
  53107. value: this._effectiveTarget[this._property]
  53108. }, {
  53109. frame: 100,
  53110. value: this.value
  53111. }
  53112. ];
  53113. var dataType;
  53114. if (typeof this.value === "number") {
  53115. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53116. }
  53117. else if (this.value instanceof BABYLON.Color3) {
  53118. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53119. }
  53120. else if (this.value instanceof BABYLON.Vector3) {
  53121. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53122. }
  53123. else if (this.value instanceof BABYLON.Matrix) {
  53124. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53125. }
  53126. else if (this.value instanceof BABYLON.Quaternion) {
  53127. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53128. }
  53129. else {
  53130. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53131. return;
  53132. }
  53133. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53134. animation.setKeys(keys);
  53135. if (this.stopOtherAnimations) {
  53136. scene.stopAnimation(this._effectiveTarget);
  53137. }
  53138. var wrapper = function () {
  53139. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53140. if (_this.onInterpolationDone) {
  53141. _this.onInterpolationDone();
  53142. }
  53143. };
  53144. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53145. };
  53146. InterpolateValueAction.prototype.serialize = function (parent) {
  53147. return _super.prototype._serialize.call(this, {
  53148. name: "InterpolateValueAction",
  53149. properties: [
  53150. BABYLON.Action._GetTargetProperty(this._target),
  53151. { name: "propertyPath", value: this.propertyPath },
  53152. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53153. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53154. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53155. ]
  53156. }, parent);
  53157. };
  53158. return InterpolateValueAction;
  53159. }(BABYLON.Action));
  53160. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53161. })(BABYLON || (BABYLON = {}));
  53162. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53163. var BABYLON;
  53164. (function (BABYLON) {
  53165. var SwitchBooleanAction = /** @class */ (function (_super) {
  53166. __extends(SwitchBooleanAction, _super);
  53167. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53168. var _this = _super.call(this, triggerOptions, condition) || this;
  53169. _this.propertyPath = propertyPath;
  53170. _this._target = _this._effectiveTarget = target;
  53171. return _this;
  53172. }
  53173. SwitchBooleanAction.prototype._prepare = function () {
  53174. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53175. this._property = this._getProperty(this.propertyPath);
  53176. };
  53177. SwitchBooleanAction.prototype.execute = function () {
  53178. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53179. };
  53180. SwitchBooleanAction.prototype.serialize = function (parent) {
  53181. return _super.prototype._serialize.call(this, {
  53182. name: "SwitchBooleanAction",
  53183. properties: [
  53184. BABYLON.Action._GetTargetProperty(this._target),
  53185. { name: "propertyPath", value: this.propertyPath }
  53186. ]
  53187. }, parent);
  53188. };
  53189. return SwitchBooleanAction;
  53190. }(BABYLON.Action));
  53191. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53192. var SetStateAction = /** @class */ (function (_super) {
  53193. __extends(SetStateAction, _super);
  53194. function SetStateAction(triggerOptions, target, value, condition) {
  53195. var _this = _super.call(this, triggerOptions, condition) || this;
  53196. _this.value = value;
  53197. _this._target = target;
  53198. return _this;
  53199. }
  53200. SetStateAction.prototype.execute = function () {
  53201. this._target.state = this.value;
  53202. };
  53203. SetStateAction.prototype.serialize = function (parent) {
  53204. return _super.prototype._serialize.call(this, {
  53205. name: "SetStateAction",
  53206. properties: [
  53207. BABYLON.Action._GetTargetProperty(this._target),
  53208. { name: "value", value: this.value }
  53209. ]
  53210. }, parent);
  53211. };
  53212. return SetStateAction;
  53213. }(BABYLON.Action));
  53214. BABYLON.SetStateAction = SetStateAction;
  53215. var SetValueAction = /** @class */ (function (_super) {
  53216. __extends(SetValueAction, _super);
  53217. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53218. var _this = _super.call(this, triggerOptions, condition) || this;
  53219. _this.propertyPath = propertyPath;
  53220. _this.value = value;
  53221. _this._target = _this._effectiveTarget = target;
  53222. return _this;
  53223. }
  53224. SetValueAction.prototype._prepare = function () {
  53225. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53226. this._property = this._getProperty(this.propertyPath);
  53227. };
  53228. SetValueAction.prototype.execute = function () {
  53229. this._effectiveTarget[this._property] = this.value;
  53230. if (this._target.markAsDirty) {
  53231. this._target.markAsDirty(this._property);
  53232. }
  53233. };
  53234. SetValueAction.prototype.serialize = function (parent) {
  53235. return _super.prototype._serialize.call(this, {
  53236. name: "SetValueAction",
  53237. properties: [
  53238. BABYLON.Action._GetTargetProperty(this._target),
  53239. { name: "propertyPath", value: this.propertyPath },
  53240. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53241. ]
  53242. }, parent);
  53243. };
  53244. return SetValueAction;
  53245. }(BABYLON.Action));
  53246. BABYLON.SetValueAction = SetValueAction;
  53247. var IncrementValueAction = /** @class */ (function (_super) {
  53248. __extends(IncrementValueAction, _super);
  53249. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53250. var _this = _super.call(this, triggerOptions, condition) || this;
  53251. _this.propertyPath = propertyPath;
  53252. _this.value = value;
  53253. _this._target = _this._effectiveTarget = target;
  53254. return _this;
  53255. }
  53256. IncrementValueAction.prototype._prepare = function () {
  53257. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53258. this._property = this._getProperty(this.propertyPath);
  53259. if (typeof this._effectiveTarget[this._property] !== "number") {
  53260. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53261. }
  53262. };
  53263. IncrementValueAction.prototype.execute = function () {
  53264. this._effectiveTarget[this._property] += this.value;
  53265. if (this._target.markAsDirty) {
  53266. this._target.markAsDirty(this._property);
  53267. }
  53268. };
  53269. IncrementValueAction.prototype.serialize = function (parent) {
  53270. return _super.prototype._serialize.call(this, {
  53271. name: "IncrementValueAction",
  53272. properties: [
  53273. BABYLON.Action._GetTargetProperty(this._target),
  53274. { name: "propertyPath", value: this.propertyPath },
  53275. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53276. ]
  53277. }, parent);
  53278. };
  53279. return IncrementValueAction;
  53280. }(BABYLON.Action));
  53281. BABYLON.IncrementValueAction = IncrementValueAction;
  53282. var PlayAnimationAction = /** @class */ (function (_super) {
  53283. __extends(PlayAnimationAction, _super);
  53284. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53285. var _this = _super.call(this, triggerOptions, condition) || this;
  53286. _this.from = from;
  53287. _this.to = to;
  53288. _this.loop = loop;
  53289. _this._target = target;
  53290. return _this;
  53291. }
  53292. PlayAnimationAction.prototype._prepare = function () {
  53293. };
  53294. PlayAnimationAction.prototype.execute = function () {
  53295. var scene = this._actionManager.getScene();
  53296. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53297. };
  53298. PlayAnimationAction.prototype.serialize = function (parent) {
  53299. return _super.prototype._serialize.call(this, {
  53300. name: "PlayAnimationAction",
  53301. properties: [
  53302. BABYLON.Action._GetTargetProperty(this._target),
  53303. { name: "from", value: String(this.from) },
  53304. { name: "to", value: String(this.to) },
  53305. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53306. ]
  53307. }, parent);
  53308. };
  53309. return PlayAnimationAction;
  53310. }(BABYLON.Action));
  53311. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53312. var StopAnimationAction = /** @class */ (function (_super) {
  53313. __extends(StopAnimationAction, _super);
  53314. function StopAnimationAction(triggerOptions, target, condition) {
  53315. var _this = _super.call(this, triggerOptions, condition) || this;
  53316. _this._target = target;
  53317. return _this;
  53318. }
  53319. StopAnimationAction.prototype._prepare = function () {
  53320. };
  53321. StopAnimationAction.prototype.execute = function () {
  53322. var scene = this._actionManager.getScene();
  53323. scene.stopAnimation(this._target);
  53324. };
  53325. StopAnimationAction.prototype.serialize = function (parent) {
  53326. return _super.prototype._serialize.call(this, {
  53327. name: "StopAnimationAction",
  53328. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53329. }, parent);
  53330. };
  53331. return StopAnimationAction;
  53332. }(BABYLON.Action));
  53333. BABYLON.StopAnimationAction = StopAnimationAction;
  53334. var DoNothingAction = /** @class */ (function (_super) {
  53335. __extends(DoNothingAction, _super);
  53336. function DoNothingAction(triggerOptions, condition) {
  53337. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53338. return _super.call(this, triggerOptions, condition) || this;
  53339. }
  53340. DoNothingAction.prototype.execute = function () {
  53341. };
  53342. DoNothingAction.prototype.serialize = function (parent) {
  53343. return _super.prototype._serialize.call(this, {
  53344. name: "DoNothingAction",
  53345. properties: []
  53346. }, parent);
  53347. };
  53348. return DoNothingAction;
  53349. }(BABYLON.Action));
  53350. BABYLON.DoNothingAction = DoNothingAction;
  53351. var CombineAction = /** @class */ (function (_super) {
  53352. __extends(CombineAction, _super);
  53353. function CombineAction(triggerOptions, children, condition) {
  53354. var _this = _super.call(this, triggerOptions, condition) || this;
  53355. _this.children = children;
  53356. return _this;
  53357. }
  53358. CombineAction.prototype._prepare = function () {
  53359. for (var index = 0; index < this.children.length; index++) {
  53360. this.children[index]._actionManager = this._actionManager;
  53361. this.children[index]._prepare();
  53362. }
  53363. };
  53364. CombineAction.prototype.execute = function (evt) {
  53365. for (var index = 0; index < this.children.length; index++) {
  53366. this.children[index].execute(evt);
  53367. }
  53368. };
  53369. CombineAction.prototype.serialize = function (parent) {
  53370. var serializationObject = _super.prototype._serialize.call(this, {
  53371. name: "CombineAction",
  53372. properties: [],
  53373. combine: []
  53374. }, parent);
  53375. for (var i = 0; i < this.children.length; i++) {
  53376. serializationObject.combine.push(this.children[i].serialize(null));
  53377. }
  53378. return serializationObject;
  53379. };
  53380. return CombineAction;
  53381. }(BABYLON.Action));
  53382. BABYLON.CombineAction = CombineAction;
  53383. var ExecuteCodeAction = /** @class */ (function (_super) {
  53384. __extends(ExecuteCodeAction, _super);
  53385. function ExecuteCodeAction(triggerOptions, func, condition) {
  53386. var _this = _super.call(this, triggerOptions, condition) || this;
  53387. _this.func = func;
  53388. return _this;
  53389. }
  53390. ExecuteCodeAction.prototype.execute = function (evt) {
  53391. this.func(evt);
  53392. };
  53393. return ExecuteCodeAction;
  53394. }(BABYLON.Action));
  53395. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53396. var SetParentAction = /** @class */ (function (_super) {
  53397. __extends(SetParentAction, _super);
  53398. function SetParentAction(triggerOptions, target, parent, condition) {
  53399. var _this = _super.call(this, triggerOptions, condition) || this;
  53400. _this._target = target;
  53401. _this._parent = parent;
  53402. return _this;
  53403. }
  53404. SetParentAction.prototype._prepare = function () {
  53405. };
  53406. SetParentAction.prototype.execute = function () {
  53407. if (this._target.parent === this._parent) {
  53408. return;
  53409. }
  53410. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53411. invertParentWorldMatrix.invert();
  53412. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53413. this._target.parent = this._parent;
  53414. };
  53415. SetParentAction.prototype.serialize = function (parent) {
  53416. return _super.prototype._serialize.call(this, {
  53417. name: "SetParentAction",
  53418. properties: [
  53419. BABYLON.Action._GetTargetProperty(this._target),
  53420. BABYLON.Action._GetTargetProperty(this._parent),
  53421. ]
  53422. }, parent);
  53423. };
  53424. return SetParentAction;
  53425. }(BABYLON.Action));
  53426. BABYLON.SetParentAction = SetParentAction;
  53427. var PlaySoundAction = /** @class */ (function (_super) {
  53428. __extends(PlaySoundAction, _super);
  53429. function PlaySoundAction(triggerOptions, sound, condition) {
  53430. var _this = _super.call(this, triggerOptions, condition) || this;
  53431. _this._sound = sound;
  53432. return _this;
  53433. }
  53434. PlaySoundAction.prototype._prepare = function () {
  53435. };
  53436. PlaySoundAction.prototype.execute = function () {
  53437. if (this._sound !== undefined)
  53438. this._sound.play();
  53439. };
  53440. PlaySoundAction.prototype.serialize = function (parent) {
  53441. return _super.prototype._serialize.call(this, {
  53442. name: "PlaySoundAction",
  53443. properties: [{ name: "sound", value: this._sound.name }]
  53444. }, parent);
  53445. };
  53446. return PlaySoundAction;
  53447. }(BABYLON.Action));
  53448. BABYLON.PlaySoundAction = PlaySoundAction;
  53449. var StopSoundAction = /** @class */ (function (_super) {
  53450. __extends(StopSoundAction, _super);
  53451. function StopSoundAction(triggerOptions, sound, condition) {
  53452. var _this = _super.call(this, triggerOptions, condition) || this;
  53453. _this._sound = sound;
  53454. return _this;
  53455. }
  53456. StopSoundAction.prototype._prepare = function () {
  53457. };
  53458. StopSoundAction.prototype.execute = function () {
  53459. if (this._sound !== undefined)
  53460. this._sound.stop();
  53461. };
  53462. StopSoundAction.prototype.serialize = function (parent) {
  53463. return _super.prototype._serialize.call(this, {
  53464. name: "StopSoundAction",
  53465. properties: [{ name: "sound", value: this._sound.name }]
  53466. }, parent);
  53467. };
  53468. return StopSoundAction;
  53469. }(BABYLON.Action));
  53470. BABYLON.StopSoundAction = StopSoundAction;
  53471. })(BABYLON || (BABYLON = {}));
  53472. //# sourceMappingURL=babylon.directActions.js.map
  53473. var BABYLON;
  53474. (function (BABYLON) {
  53475. var SpriteManager = /** @class */ (function () {
  53476. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53477. if (epsilon === void 0) { epsilon = 0.01; }
  53478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53479. this.name = name;
  53480. this.sprites = new Array();
  53481. this.renderingGroupId = 0;
  53482. this.layerMask = 0x0FFFFFFF;
  53483. this.fogEnabled = true;
  53484. this.isPickable = false;
  53485. /**
  53486. * An event triggered when the manager is disposed.
  53487. */
  53488. this.onDisposeObservable = new BABYLON.Observable();
  53489. this._vertexBuffers = {};
  53490. this._capacity = capacity;
  53491. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53492. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53493. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53494. if (cellSize.width && cellSize.height) {
  53495. this.cellWidth = cellSize.width;
  53496. this.cellHeight = cellSize.height;
  53497. }
  53498. else if (cellSize !== undefined) {
  53499. this.cellWidth = cellSize;
  53500. this.cellHeight = cellSize;
  53501. }
  53502. else {
  53503. return;
  53504. }
  53505. this._epsilon = epsilon;
  53506. this._scene = scene;
  53507. this._scene.spriteManagers.push(this);
  53508. var indices = [];
  53509. var index = 0;
  53510. for (var count = 0; count < capacity; count++) {
  53511. indices.push(index);
  53512. indices.push(index + 1);
  53513. indices.push(index + 2);
  53514. indices.push(index);
  53515. indices.push(index + 2);
  53516. indices.push(index + 3);
  53517. index += 4;
  53518. }
  53519. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53520. // VBO
  53521. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53522. this._vertexData = new Float32Array(capacity * 16 * 4);
  53523. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53524. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53525. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53526. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53527. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53528. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53529. this._vertexBuffers["options"] = options;
  53530. this._vertexBuffers["cellInfo"] = cellInfo;
  53531. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53532. // Effects
  53533. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53534. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53535. }
  53536. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53537. set: function (callback) {
  53538. if (this._onDisposeObserver) {
  53539. this.onDisposeObservable.remove(this._onDisposeObserver);
  53540. }
  53541. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(SpriteManager.prototype, "texture", {
  53547. get: function () {
  53548. return this._spriteTexture;
  53549. },
  53550. set: function (value) {
  53551. this._spriteTexture = value;
  53552. },
  53553. enumerable: true,
  53554. configurable: true
  53555. });
  53556. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53557. var arrayOffset = index * 16;
  53558. if (offsetX === 0)
  53559. offsetX = this._epsilon;
  53560. else if (offsetX === 1)
  53561. offsetX = 1 - this._epsilon;
  53562. if (offsetY === 0)
  53563. offsetY = this._epsilon;
  53564. else if (offsetY === 1)
  53565. offsetY = 1 - this._epsilon;
  53566. this._vertexData[arrayOffset] = sprite.position.x;
  53567. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53568. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53569. this._vertexData[arrayOffset + 3] = sprite.angle;
  53570. this._vertexData[arrayOffset + 4] = sprite.width;
  53571. this._vertexData[arrayOffset + 5] = sprite.height;
  53572. this._vertexData[arrayOffset + 6] = offsetX;
  53573. this._vertexData[arrayOffset + 7] = offsetY;
  53574. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53575. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53576. var offset = (sprite.cellIndex / rowSize) >> 0;
  53577. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53578. this._vertexData[arrayOffset + 11] = offset;
  53579. // Color
  53580. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53581. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53582. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53583. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53584. };
  53585. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53586. var count = Math.min(this._capacity, this.sprites.length);
  53587. var min = BABYLON.Vector3.Zero();
  53588. var max = BABYLON.Vector3.Zero();
  53589. var distance = Number.MAX_VALUE;
  53590. var currentSprite = null;
  53591. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53592. var cameraView = camera.getViewMatrix();
  53593. for (var index = 0; index < count; index++) {
  53594. var sprite = this.sprites[index];
  53595. if (!sprite) {
  53596. continue;
  53597. }
  53598. if (predicate) {
  53599. if (!predicate(sprite)) {
  53600. continue;
  53601. }
  53602. }
  53603. else if (!sprite.isPickable) {
  53604. continue;
  53605. }
  53606. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53607. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53608. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53609. if (ray.intersectsBoxMinMax(min, max)) {
  53610. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53611. if (distance > currentDistance) {
  53612. distance = currentDistance;
  53613. currentSprite = sprite;
  53614. if (fastCheck) {
  53615. break;
  53616. }
  53617. }
  53618. }
  53619. }
  53620. if (currentSprite) {
  53621. var result = new BABYLON.PickingInfo();
  53622. result.hit = true;
  53623. result.pickedSprite = currentSprite;
  53624. result.distance = distance;
  53625. return result;
  53626. }
  53627. return null;
  53628. };
  53629. SpriteManager.prototype.render = function () {
  53630. // Check
  53631. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53632. return;
  53633. var engine = this._scene.getEngine();
  53634. var baseSize = this._spriteTexture.getBaseSize();
  53635. // Sprites
  53636. var deltaTime = engine.getDeltaTime();
  53637. var max = Math.min(this._capacity, this.sprites.length);
  53638. var rowSize = baseSize.width / this.cellWidth;
  53639. var offset = 0;
  53640. for (var index = 0; index < max; index++) {
  53641. var sprite = this.sprites[index];
  53642. if (!sprite || !sprite.isVisible) {
  53643. continue;
  53644. }
  53645. sprite._animate(deltaTime);
  53646. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53647. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53648. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53649. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53650. }
  53651. this._buffer.update(this._vertexData);
  53652. // Render
  53653. var effect = this._effectBase;
  53654. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53655. effect = this._effectFog;
  53656. }
  53657. engine.enableEffect(effect);
  53658. var viewMatrix = this._scene.getViewMatrix();
  53659. effect.setTexture("diffuseSampler", this._spriteTexture);
  53660. effect.setMatrix("view", viewMatrix);
  53661. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53662. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53663. // Fog
  53664. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53665. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53666. effect.setColor3("vFogColor", this._scene.fogColor);
  53667. }
  53668. // VBOs
  53669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53670. // Draw order
  53671. engine.setDepthFunctionToLessOrEqual();
  53672. effect.setBool("alphaTest", true);
  53673. engine.setColorWrite(false);
  53674. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53675. engine.setColorWrite(true);
  53676. effect.setBool("alphaTest", false);
  53677. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53678. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53679. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53680. };
  53681. SpriteManager.prototype.dispose = function () {
  53682. if (this._buffer) {
  53683. this._buffer.dispose();
  53684. this._buffer = null;
  53685. }
  53686. if (this._indexBuffer) {
  53687. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53688. this._indexBuffer = null;
  53689. }
  53690. if (this._spriteTexture) {
  53691. this._spriteTexture.dispose();
  53692. this._spriteTexture = null;
  53693. }
  53694. // Remove from scene
  53695. var index = this._scene.spriteManagers.indexOf(this);
  53696. this._scene.spriteManagers.splice(index, 1);
  53697. // Callback
  53698. this.onDisposeObservable.notifyObservers(this);
  53699. this.onDisposeObservable.clear();
  53700. };
  53701. return SpriteManager;
  53702. }());
  53703. BABYLON.SpriteManager = SpriteManager;
  53704. })(BABYLON || (BABYLON = {}));
  53705. //# sourceMappingURL=babylon.spriteManager.js.map
  53706. var BABYLON;
  53707. (function (BABYLON) {
  53708. var Sprite = /** @class */ (function () {
  53709. function Sprite(name, manager) {
  53710. this.name = name;
  53711. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53712. this.width = 1.0;
  53713. this.height = 1.0;
  53714. this.angle = 0;
  53715. this.cellIndex = 0;
  53716. this.invertU = 0;
  53717. this.invertV = 0;
  53718. this.animations = new Array();
  53719. this.isPickable = false;
  53720. this._animationStarted = false;
  53721. this._loopAnimation = false;
  53722. this._fromIndex = 0;
  53723. this._toIndex = 0;
  53724. this._delay = 0;
  53725. this._direction = 1;
  53726. this._time = 0;
  53727. /**
  53728. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53729. */
  53730. this.isVisible = true;
  53731. this._manager = manager;
  53732. this._manager.sprites.push(this);
  53733. this.position = BABYLON.Vector3.Zero();
  53734. }
  53735. Object.defineProperty(Sprite.prototype, "size", {
  53736. get: function () {
  53737. return this.width;
  53738. },
  53739. set: function (value) {
  53740. this.width = value;
  53741. this.height = value;
  53742. },
  53743. enumerable: true,
  53744. configurable: true
  53745. });
  53746. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53747. this._fromIndex = from;
  53748. this._toIndex = to;
  53749. this._loopAnimation = loop;
  53750. this._delay = delay;
  53751. this._animationStarted = true;
  53752. this._direction = from < to ? 1 : -1;
  53753. this.cellIndex = from;
  53754. this._time = 0;
  53755. this._onAnimationEnd = onAnimationEnd;
  53756. };
  53757. Sprite.prototype.stopAnimation = function () {
  53758. this._animationStarted = false;
  53759. };
  53760. Sprite.prototype._animate = function (deltaTime) {
  53761. if (!this._animationStarted)
  53762. return;
  53763. this._time += deltaTime;
  53764. if (this._time > this._delay) {
  53765. this._time = this._time % this._delay;
  53766. this.cellIndex += this._direction;
  53767. if (this.cellIndex > this._toIndex) {
  53768. if (this._loopAnimation) {
  53769. this.cellIndex = this._fromIndex;
  53770. }
  53771. else {
  53772. this.cellIndex = this._toIndex;
  53773. this._animationStarted = false;
  53774. if (this._onAnimationEnd) {
  53775. this._onAnimationEnd();
  53776. }
  53777. if (this.disposeWhenFinishedAnimating) {
  53778. this.dispose();
  53779. }
  53780. }
  53781. }
  53782. }
  53783. };
  53784. Sprite.prototype.dispose = function () {
  53785. for (var i = 0; i < this._manager.sprites.length; i++) {
  53786. if (this._manager.sprites[i] == this) {
  53787. this._manager.sprites.splice(i, 1);
  53788. }
  53789. }
  53790. };
  53791. return Sprite;
  53792. }());
  53793. BABYLON.Sprite = Sprite;
  53794. })(BABYLON || (BABYLON = {}));
  53795. //# sourceMappingURL=babylon.sprite.js.map
  53796. var BABYLON;
  53797. (function (BABYLON) {
  53798. var IntersectionInfo = /** @class */ (function () {
  53799. function IntersectionInfo(bu, bv, distance) {
  53800. this.bu = bu;
  53801. this.bv = bv;
  53802. this.distance = distance;
  53803. this.faceId = 0;
  53804. this.subMeshId = 0;
  53805. }
  53806. return IntersectionInfo;
  53807. }());
  53808. BABYLON.IntersectionInfo = IntersectionInfo;
  53809. /**
  53810. * Information about the result of picking within a scene
  53811. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53812. */
  53813. var PickingInfo = /** @class */ (function () {
  53814. function PickingInfo() {
  53815. /**
  53816. * If the pick collided with an object
  53817. */
  53818. this.hit = false;
  53819. /**
  53820. * Distance away where the pick collided
  53821. */
  53822. this.distance = 0;
  53823. /**
  53824. * The location of pick collision
  53825. */
  53826. this.pickedPoint = null;
  53827. /**
  53828. * The mesh corrisponding the the pick collision
  53829. */
  53830. this.pickedMesh = null;
  53831. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53832. this.bu = 0;
  53833. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53834. this.bv = 0;
  53835. /** The id of the face on the mesh that was picked */
  53836. this.faceId = -1;
  53837. /** Id of the the submesh that was picked */
  53838. this.subMeshId = 0;
  53839. /** If a sprite was picked, this will be the sprite the pick collided with */
  53840. this.pickedSprite = null;
  53841. /**
  53842. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53843. */
  53844. this.originMesh = null;
  53845. /**
  53846. * The ray that was used to perform the picking.
  53847. */
  53848. this.ray = null;
  53849. }
  53850. /**
  53851. * Gets the normal corrispodning to the face the pick collided with
  53852. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53853. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53854. * @returns The normal corrispodning to the face the pick collided with
  53855. */
  53856. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53857. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53858. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53859. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53860. return null;
  53861. }
  53862. var indices = this.pickedMesh.getIndices();
  53863. if (!indices) {
  53864. return null;
  53865. }
  53866. var result;
  53867. if (useVerticesNormals) {
  53868. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53869. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53870. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53871. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53872. normal0 = normal0.scale(this.bu);
  53873. normal1 = normal1.scale(this.bv);
  53874. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53875. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53876. }
  53877. else {
  53878. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53879. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53880. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53881. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53882. var p1p2 = vertex1.subtract(vertex2);
  53883. var p3p2 = vertex3.subtract(vertex2);
  53884. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53885. }
  53886. if (useWorldCoordinates) {
  53887. var wm = this.pickedMesh.getWorldMatrix();
  53888. if (this.pickedMesh.nonUniformScaling) {
  53889. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53890. wm = BABYLON.Tmp.Matrix[0];
  53891. wm.setTranslationFromFloats(0, 0, 0);
  53892. wm.invert();
  53893. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53894. wm = BABYLON.Tmp.Matrix[1];
  53895. }
  53896. result = BABYLON.Vector3.TransformNormal(result, wm);
  53897. }
  53898. result.normalize();
  53899. return result;
  53900. };
  53901. /**
  53902. * Gets the texture coordinates of where the pick occured
  53903. * @returns the vector containing the coordnates of the texture
  53904. */
  53905. PickingInfo.prototype.getTextureCoordinates = function () {
  53906. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53907. return null;
  53908. }
  53909. var indices = this.pickedMesh.getIndices();
  53910. if (!indices) {
  53911. return null;
  53912. }
  53913. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53914. if (!uvs) {
  53915. return null;
  53916. }
  53917. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53918. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53919. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53920. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53921. uv1 = uv1.scale(this.bu);
  53922. uv2 = uv2.scale(this.bv);
  53923. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53924. };
  53925. return PickingInfo;
  53926. }());
  53927. BABYLON.PickingInfo = PickingInfo;
  53928. })(BABYLON || (BABYLON = {}));
  53929. //# sourceMappingURL=babylon.pickingInfo.js.map
  53930. var BABYLON;
  53931. (function (BABYLON) {
  53932. var Ray = /** @class */ (function () {
  53933. function Ray(origin, direction, length) {
  53934. if (length === void 0) { length = Number.MAX_VALUE; }
  53935. this.origin = origin;
  53936. this.direction = direction;
  53937. this.length = length;
  53938. }
  53939. // Methods
  53940. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53941. var d = 0.0;
  53942. var maxValue = Number.MAX_VALUE;
  53943. var inv;
  53944. var min;
  53945. var max;
  53946. var temp;
  53947. if (Math.abs(this.direction.x) < 0.0000001) {
  53948. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53949. return false;
  53950. }
  53951. }
  53952. else {
  53953. inv = 1.0 / this.direction.x;
  53954. min = (minimum.x - this.origin.x) * inv;
  53955. max = (maximum.x - this.origin.x) * inv;
  53956. if (max === -Infinity) {
  53957. max = Infinity;
  53958. }
  53959. if (min > max) {
  53960. temp = min;
  53961. min = max;
  53962. max = temp;
  53963. }
  53964. d = Math.max(min, d);
  53965. maxValue = Math.min(max, maxValue);
  53966. if (d > maxValue) {
  53967. return false;
  53968. }
  53969. }
  53970. if (Math.abs(this.direction.y) < 0.0000001) {
  53971. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53972. return false;
  53973. }
  53974. }
  53975. else {
  53976. inv = 1.0 / this.direction.y;
  53977. min = (minimum.y - this.origin.y) * inv;
  53978. max = (maximum.y - this.origin.y) * inv;
  53979. if (max === -Infinity) {
  53980. max = Infinity;
  53981. }
  53982. if (min > max) {
  53983. temp = min;
  53984. min = max;
  53985. max = temp;
  53986. }
  53987. d = Math.max(min, d);
  53988. maxValue = Math.min(max, maxValue);
  53989. if (d > maxValue) {
  53990. return false;
  53991. }
  53992. }
  53993. if (Math.abs(this.direction.z) < 0.0000001) {
  53994. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53995. return false;
  53996. }
  53997. }
  53998. else {
  53999. inv = 1.0 / this.direction.z;
  54000. min = (minimum.z - this.origin.z) * inv;
  54001. max = (maximum.z - this.origin.z) * inv;
  54002. if (max === -Infinity) {
  54003. max = Infinity;
  54004. }
  54005. if (min > max) {
  54006. temp = min;
  54007. min = max;
  54008. max = temp;
  54009. }
  54010. d = Math.max(min, d);
  54011. maxValue = Math.min(max, maxValue);
  54012. if (d > maxValue) {
  54013. return false;
  54014. }
  54015. }
  54016. return true;
  54017. };
  54018. Ray.prototype.intersectsBox = function (box) {
  54019. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54020. };
  54021. Ray.prototype.intersectsSphere = function (sphere) {
  54022. var x = sphere.center.x - this.origin.x;
  54023. var y = sphere.center.y - this.origin.y;
  54024. var z = sphere.center.z - this.origin.z;
  54025. var pyth = (x * x) + (y * y) + (z * z);
  54026. var rr = sphere.radius * sphere.radius;
  54027. if (pyth <= rr) {
  54028. return true;
  54029. }
  54030. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54031. if (dot < 0.0) {
  54032. return false;
  54033. }
  54034. var temp = pyth - (dot * dot);
  54035. return temp <= rr;
  54036. };
  54037. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54038. if (!this._edge1) {
  54039. this._edge1 = BABYLON.Vector3.Zero();
  54040. this._edge2 = BABYLON.Vector3.Zero();
  54041. this._pvec = BABYLON.Vector3.Zero();
  54042. this._tvec = BABYLON.Vector3.Zero();
  54043. this._qvec = BABYLON.Vector3.Zero();
  54044. }
  54045. vertex1.subtractToRef(vertex0, this._edge1);
  54046. vertex2.subtractToRef(vertex0, this._edge2);
  54047. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54048. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54049. if (det === 0) {
  54050. return null;
  54051. }
  54052. var invdet = 1 / det;
  54053. this.origin.subtractToRef(vertex0, this._tvec);
  54054. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54055. if (bu < 0 || bu > 1.0) {
  54056. return null;
  54057. }
  54058. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54059. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54060. if (bv < 0 || bu + bv > 1.0) {
  54061. return null;
  54062. }
  54063. //check if the distance is longer than the predefined length.
  54064. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54065. if (distance > this.length) {
  54066. return null;
  54067. }
  54068. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54069. };
  54070. Ray.prototype.intersectsPlane = function (plane) {
  54071. var distance;
  54072. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54073. if (Math.abs(result1) < 9.99999997475243E-07) {
  54074. return null;
  54075. }
  54076. else {
  54077. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54078. distance = (-plane.d - result2) / result1;
  54079. if (distance < 0.0) {
  54080. if (distance < -9.99999997475243E-07) {
  54081. return null;
  54082. }
  54083. else {
  54084. return 0;
  54085. }
  54086. }
  54087. return distance;
  54088. }
  54089. };
  54090. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54091. var tm = BABYLON.Tmp.Matrix[0];
  54092. mesh.getWorldMatrix().invertToRef(tm);
  54093. if (this._tmpRay) {
  54094. Ray.TransformToRef(this, tm, this._tmpRay);
  54095. }
  54096. else {
  54097. this._tmpRay = Ray.Transform(this, tm);
  54098. }
  54099. return mesh.intersects(this._tmpRay, fastCheck);
  54100. };
  54101. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54102. if (results) {
  54103. results.length = 0;
  54104. }
  54105. else {
  54106. results = [];
  54107. }
  54108. for (var i = 0; i < meshes.length; i++) {
  54109. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54110. if (pickInfo.hit) {
  54111. results.push(pickInfo);
  54112. }
  54113. }
  54114. results.sort(this._comparePickingInfo);
  54115. return results;
  54116. };
  54117. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54118. if (pickingInfoA.distance < pickingInfoB.distance) {
  54119. return -1;
  54120. }
  54121. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54122. return 1;
  54123. }
  54124. else {
  54125. return 0;
  54126. }
  54127. };
  54128. /**
  54129. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54130. * @param sega the first point of the segment to test the intersection against
  54131. * @param segb the second point of the segment to test the intersection against
  54132. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54133. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54134. */
  54135. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54136. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54137. var u = segb.subtract(sega);
  54138. var v = rsegb.subtract(this.origin);
  54139. var w = sega.subtract(this.origin);
  54140. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54141. var b = BABYLON.Vector3.Dot(u, v);
  54142. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54143. var d = BABYLON.Vector3.Dot(u, w);
  54144. var e = BABYLON.Vector3.Dot(v, w);
  54145. var D = a * c - b * b; // always >= 0
  54146. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54147. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54148. // compute the line parameters of the two closest points
  54149. if (D < Ray.smallnum) { // the lines are almost parallel
  54150. sN = 0.0; // force using point P0 on segment S1
  54151. sD = 1.0; // to prevent possible division by 0.0 later
  54152. tN = e;
  54153. tD = c;
  54154. }
  54155. else { // get the closest points on the infinite lines
  54156. sN = (b * e - c * d);
  54157. tN = (a * e - b * d);
  54158. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54159. sN = 0.0;
  54160. tN = e;
  54161. tD = c;
  54162. }
  54163. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54164. sN = sD;
  54165. tN = e + b;
  54166. tD = c;
  54167. }
  54168. }
  54169. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54170. tN = 0.0;
  54171. // recompute sc for this edge
  54172. if (-d < 0.0) {
  54173. sN = 0.0;
  54174. }
  54175. else if (-d > a)
  54176. sN = sD;
  54177. else {
  54178. sN = -d;
  54179. sD = a;
  54180. }
  54181. }
  54182. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54183. tN = tD;
  54184. // recompute sc for this edge
  54185. if ((-d + b) < 0.0) {
  54186. sN = 0;
  54187. }
  54188. else if ((-d + b) > a) {
  54189. sN = sD;
  54190. }
  54191. else {
  54192. sN = (-d + b);
  54193. sD = a;
  54194. }
  54195. }
  54196. // finally do the division to get sc and tc
  54197. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54198. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54199. // get the difference of the two closest points
  54200. var qtc = v.multiplyByFloats(tc, tc, tc);
  54201. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54202. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54203. if (isIntersected) {
  54204. return qtc.length();
  54205. }
  54206. return -1;
  54207. };
  54208. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54209. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54210. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54211. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54212. this.direction.normalize();
  54213. return this;
  54214. };
  54215. // Statics
  54216. Ray.Zero = function () {
  54217. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54218. };
  54219. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54220. var result = Ray.Zero();
  54221. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54222. };
  54223. /**
  54224. * 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
  54225. * transformed to the given world matrix.
  54226. * @param origin The origin point
  54227. * @param end The end point
  54228. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54229. */
  54230. Ray.CreateNewFromTo = function (origin, end, world) {
  54231. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54232. var direction = end.subtract(origin);
  54233. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54234. direction.normalize();
  54235. return Ray.Transform(new Ray(origin, direction, length), world);
  54236. };
  54237. Ray.Transform = function (ray, matrix) {
  54238. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54239. Ray.TransformToRef(ray, matrix, result);
  54240. return result;
  54241. };
  54242. Ray.TransformToRef = function (ray, matrix, result) {
  54243. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54244. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54245. result.length = ray.length;
  54246. var dir = result.direction;
  54247. var len = dir.length();
  54248. if (!(len === 0 || len === 1)) {
  54249. var num = 1.0 / len;
  54250. dir.x *= num;
  54251. dir.y *= num;
  54252. dir.z *= num;
  54253. result.length *= len;
  54254. }
  54255. };
  54256. Ray.smallnum = 0.00000001;
  54257. Ray.rayl = 10e8;
  54258. return Ray;
  54259. }());
  54260. BABYLON.Ray = Ray;
  54261. })(BABYLON || (BABYLON = {}));
  54262. //# sourceMappingURL=babylon.ray.js.map
  54263. var BABYLON;
  54264. (function (BABYLON) {
  54265. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54266. if (boxMin.x > sphereCenter.x + sphereRadius)
  54267. return false;
  54268. if (sphereCenter.x - sphereRadius > boxMax.x)
  54269. return false;
  54270. if (boxMin.y > sphereCenter.y + sphereRadius)
  54271. return false;
  54272. if (sphereCenter.y - sphereRadius > boxMax.y)
  54273. return false;
  54274. if (boxMin.z > sphereCenter.z + sphereRadius)
  54275. return false;
  54276. if (sphereCenter.z - sphereRadius > boxMax.z)
  54277. return false;
  54278. return true;
  54279. };
  54280. var getLowestRoot = (function () {
  54281. var result = { root: 0, found: false };
  54282. return function (a, b, c, maxR) {
  54283. result.root = 0;
  54284. result.found = false;
  54285. var determinant = b * b - 4.0 * a * c;
  54286. if (determinant < 0)
  54287. return result;
  54288. var sqrtD = Math.sqrt(determinant);
  54289. var r1 = (-b - sqrtD) / (2.0 * a);
  54290. var r2 = (-b + sqrtD) / (2.0 * a);
  54291. if (r1 > r2) {
  54292. var temp = r2;
  54293. r2 = r1;
  54294. r1 = temp;
  54295. }
  54296. if (r1 > 0 && r1 < maxR) {
  54297. result.root = r1;
  54298. result.found = true;
  54299. return result;
  54300. }
  54301. if (r2 > 0 && r2 < maxR) {
  54302. result.root = r2;
  54303. result.found = true;
  54304. return result;
  54305. }
  54306. return result;
  54307. };
  54308. })();
  54309. var Collider = /** @class */ (function () {
  54310. function Collider() {
  54311. this._collisionPoint = BABYLON.Vector3.Zero();
  54312. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54313. this._tempVector = BABYLON.Vector3.Zero();
  54314. this._tempVector2 = BABYLON.Vector3.Zero();
  54315. this._tempVector3 = BABYLON.Vector3.Zero();
  54316. this._tempVector4 = BABYLON.Vector3.Zero();
  54317. this._edge = BABYLON.Vector3.Zero();
  54318. this._baseToVertex = BABYLON.Vector3.Zero();
  54319. this._destinationPoint = BABYLON.Vector3.Zero();
  54320. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54321. this._displacementVector = BABYLON.Vector3.Zero();
  54322. this._radius = BABYLON.Vector3.One();
  54323. this._retry = 0;
  54324. this._basePointWorld = BABYLON.Vector3.Zero();
  54325. this._velocityWorld = BABYLON.Vector3.Zero();
  54326. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54327. this._collisionMask = -1;
  54328. }
  54329. Object.defineProperty(Collider.prototype, "collisionMask", {
  54330. get: function () {
  54331. return this._collisionMask;
  54332. },
  54333. set: function (mask) {
  54334. this._collisionMask = !isNaN(mask) ? mask : -1;
  54335. },
  54336. enumerable: true,
  54337. configurable: true
  54338. });
  54339. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54340. /**
  54341. * Gets the plane normal used to compute the sliding response (in local space)
  54342. */
  54343. get: function () {
  54344. return this._slidePlaneNormal;
  54345. },
  54346. enumerable: true,
  54347. configurable: true
  54348. });
  54349. // Methods
  54350. Collider.prototype._initialize = function (source, dir, e) {
  54351. this._velocity = dir;
  54352. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54353. this._basePoint = source;
  54354. source.multiplyToRef(this._radius, this._basePointWorld);
  54355. dir.multiplyToRef(this._radius, this._velocityWorld);
  54356. this._velocityWorldLength = this._velocityWorld.length();
  54357. this._epsilon = e;
  54358. this.collisionFound = false;
  54359. };
  54360. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54361. pa.subtractToRef(point, this._tempVector);
  54362. pb.subtractToRef(point, this._tempVector2);
  54363. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54364. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54365. if (d < 0)
  54366. return false;
  54367. pc.subtractToRef(point, this._tempVector3);
  54368. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54369. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54370. if (d < 0)
  54371. return false;
  54372. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54373. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54374. return d >= 0;
  54375. };
  54376. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54377. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54378. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54379. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54380. return false;
  54381. }
  54382. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54383. return false;
  54384. return true;
  54385. };
  54386. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54387. var t0;
  54388. var embeddedInPlane = false;
  54389. //defensive programming, actually not needed.
  54390. if (!trianglePlaneArray) {
  54391. trianglePlaneArray = [];
  54392. }
  54393. if (!trianglePlaneArray[faceIndex]) {
  54394. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54395. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54396. }
  54397. var trianglePlane = trianglePlaneArray[faceIndex];
  54398. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54399. return;
  54400. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54401. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54402. if (normalDotVelocity == 0) {
  54403. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54404. return;
  54405. embeddedInPlane = true;
  54406. t0 = 0;
  54407. }
  54408. else {
  54409. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54410. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54411. if (t0 > t1) {
  54412. var temp = t1;
  54413. t1 = t0;
  54414. t0 = temp;
  54415. }
  54416. if (t0 > 1.0 || t1 < 0.0)
  54417. return;
  54418. if (t0 < 0)
  54419. t0 = 0;
  54420. if (t0 > 1.0)
  54421. t0 = 1.0;
  54422. }
  54423. this._collisionPoint.copyFromFloats(0, 0, 0);
  54424. var found = false;
  54425. var t = 1.0;
  54426. if (!embeddedInPlane) {
  54427. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54428. this._velocity.scaleToRef(t0, this._tempVector);
  54429. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54430. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54431. found = true;
  54432. t = t0;
  54433. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54434. }
  54435. }
  54436. if (!found) {
  54437. var velocitySquaredLength = this._velocity.lengthSquared();
  54438. var a = velocitySquaredLength;
  54439. this._basePoint.subtractToRef(p1, this._tempVector);
  54440. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54441. var c = this._tempVector.lengthSquared() - 1.0;
  54442. var lowestRoot = getLowestRoot(a, b, c, t);
  54443. if (lowestRoot.found) {
  54444. t = lowestRoot.root;
  54445. found = true;
  54446. this._collisionPoint.copyFrom(p1);
  54447. }
  54448. this._basePoint.subtractToRef(p2, this._tempVector);
  54449. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54450. c = this._tempVector.lengthSquared() - 1.0;
  54451. lowestRoot = getLowestRoot(a, b, c, t);
  54452. if (lowestRoot.found) {
  54453. t = lowestRoot.root;
  54454. found = true;
  54455. this._collisionPoint.copyFrom(p2);
  54456. }
  54457. this._basePoint.subtractToRef(p3, this._tempVector);
  54458. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54459. c = this._tempVector.lengthSquared() - 1.0;
  54460. lowestRoot = getLowestRoot(a, b, c, t);
  54461. if (lowestRoot.found) {
  54462. t = lowestRoot.root;
  54463. found = true;
  54464. this._collisionPoint.copyFrom(p3);
  54465. }
  54466. p2.subtractToRef(p1, this._edge);
  54467. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54468. var edgeSquaredLength = this._edge.lengthSquared();
  54469. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54470. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54471. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54472. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54473. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54474. lowestRoot = getLowestRoot(a, b, c, t);
  54475. if (lowestRoot.found) {
  54476. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54477. if (f >= 0.0 && f <= 1.0) {
  54478. t = lowestRoot.root;
  54479. found = true;
  54480. this._edge.scaleInPlace(f);
  54481. p1.addToRef(this._edge, this._collisionPoint);
  54482. }
  54483. }
  54484. p3.subtractToRef(p2, this._edge);
  54485. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54486. edgeSquaredLength = this._edge.lengthSquared();
  54487. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54488. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54489. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54490. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54491. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54492. lowestRoot = getLowestRoot(a, b, c, t);
  54493. if (lowestRoot.found) {
  54494. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54495. if (f >= 0.0 && f <= 1.0) {
  54496. t = lowestRoot.root;
  54497. found = true;
  54498. this._edge.scaleInPlace(f);
  54499. p2.addToRef(this._edge, this._collisionPoint);
  54500. }
  54501. }
  54502. p1.subtractToRef(p3, this._edge);
  54503. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54504. edgeSquaredLength = this._edge.lengthSquared();
  54505. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54506. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54507. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54508. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54509. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54510. lowestRoot = getLowestRoot(a, b, c, t);
  54511. if (lowestRoot.found) {
  54512. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54513. if (f >= 0.0 && f <= 1.0) {
  54514. t = lowestRoot.root;
  54515. found = true;
  54516. this._edge.scaleInPlace(f);
  54517. p3.addToRef(this._edge, this._collisionPoint);
  54518. }
  54519. }
  54520. }
  54521. if (found) {
  54522. var distToCollision = t * this._velocity.length();
  54523. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54524. if (!this.intersectionPoint) {
  54525. this.intersectionPoint = this._collisionPoint.clone();
  54526. }
  54527. else {
  54528. this.intersectionPoint.copyFrom(this._collisionPoint);
  54529. }
  54530. this._nearestDistance = distToCollision;
  54531. this.collisionFound = true;
  54532. }
  54533. }
  54534. };
  54535. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54536. for (var i = indexStart; i < indexEnd; i += 3) {
  54537. var p1 = pts[indices[i] - decal];
  54538. var p2 = pts[indices[i + 1] - decal];
  54539. var p3 = pts[indices[i + 2] - decal];
  54540. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54541. }
  54542. };
  54543. Collider.prototype._getResponse = function (pos, vel) {
  54544. pos.addToRef(vel, this._destinationPoint);
  54545. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54546. this._basePoint.addToRef(vel, pos);
  54547. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54548. this._slidePlaneNormal.normalize();
  54549. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54550. pos.addInPlace(this._displacementVector);
  54551. this.intersectionPoint.addInPlace(this._displacementVector);
  54552. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54553. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54554. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54555. };
  54556. return Collider;
  54557. }());
  54558. BABYLON.Collider = Collider;
  54559. })(BABYLON || (BABYLON = {}));
  54560. //# sourceMappingURL=babylon.collider.js.map
  54561. var BABYLON;
  54562. (function (BABYLON) {
  54563. //WebWorker code will be inserted to this variable.
  54564. BABYLON.CollisionWorker = "";
  54565. /** Defines supported task for worker process */
  54566. var WorkerTaskType;
  54567. (function (WorkerTaskType) {
  54568. /** Initialization */
  54569. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54570. /** Update of geometry */
  54571. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54572. /** Evaluate collision */
  54573. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54574. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54575. /** Defines kind of replies returned by worker */
  54576. var WorkerReplyType;
  54577. (function (WorkerReplyType) {
  54578. /** Success */
  54579. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54580. /** Unkown error */
  54581. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54582. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54583. var CollisionCoordinatorWorker = /** @class */ (function () {
  54584. function CollisionCoordinatorWorker() {
  54585. var _this = this;
  54586. this._scaledPosition = BABYLON.Vector3.Zero();
  54587. this._scaledVelocity = BABYLON.Vector3.Zero();
  54588. this.onMeshUpdated = function (transformNode) {
  54589. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54590. };
  54591. this.onGeometryUpdated = function (geometry) {
  54592. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54593. };
  54594. this._afterRender = function () {
  54595. if (!_this._init)
  54596. return;
  54597. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54598. return;
  54599. }
  54600. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54601. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54602. if (_this._runningUpdated > 4) {
  54603. return;
  54604. }
  54605. ++_this._runningUpdated;
  54606. var payload = {
  54607. updatedMeshes: _this._addUpdateMeshesList,
  54608. updatedGeometries: _this._addUpdateGeometriesList,
  54609. removedGeometries: _this._toRemoveGeometryArray,
  54610. removedMeshes: _this._toRemoveMeshesArray
  54611. };
  54612. var message = {
  54613. payload: payload,
  54614. taskType: WorkerTaskType.UPDATE
  54615. };
  54616. var serializable = [];
  54617. for (var id in payload.updatedGeometries) {
  54618. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54619. //prepare transferables
  54620. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54621. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54622. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54623. }
  54624. }
  54625. _this._worker.postMessage(message, serializable);
  54626. _this._addUpdateMeshesList = {};
  54627. _this._addUpdateGeometriesList = {};
  54628. _this._toRemoveGeometryArray = [];
  54629. _this._toRemoveMeshesArray = [];
  54630. };
  54631. this._onMessageFromWorker = function (e) {
  54632. var returnData = e.data;
  54633. if (returnData.error != WorkerReplyType.SUCCESS) {
  54634. //TODO what errors can be returned from the worker?
  54635. BABYLON.Tools.Warn("error returned from worker!");
  54636. return;
  54637. }
  54638. switch (returnData.taskType) {
  54639. case WorkerTaskType.INIT:
  54640. _this._init = true;
  54641. //Update the worked with ALL of the scene's current state
  54642. _this._scene.meshes.forEach(function (mesh) {
  54643. _this.onMeshAdded(mesh);
  54644. });
  54645. _this._scene.getGeometries().forEach(function (geometry) {
  54646. _this.onGeometryAdded(geometry);
  54647. });
  54648. break;
  54649. case WorkerTaskType.UPDATE:
  54650. _this._runningUpdated--;
  54651. break;
  54652. case WorkerTaskType.COLLIDE:
  54653. var returnPayload = returnData.payload;
  54654. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54655. return;
  54656. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54657. if (callback) {
  54658. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54659. if (mesh) {
  54660. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54661. }
  54662. }
  54663. //cleanup
  54664. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54665. break;
  54666. }
  54667. };
  54668. this._collisionsCallbackArray = [];
  54669. this._init = false;
  54670. this._runningUpdated = 0;
  54671. this._addUpdateMeshesList = {};
  54672. this._addUpdateGeometriesList = {};
  54673. this._toRemoveGeometryArray = [];
  54674. this._toRemoveMeshesArray = [];
  54675. }
  54676. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54677. if (!this._init)
  54678. return;
  54679. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54680. return;
  54681. position.divideToRef(collider._radius, this._scaledPosition);
  54682. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54683. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54684. var payload = {
  54685. collider: {
  54686. position: this._scaledPosition.asArray(),
  54687. velocity: this._scaledVelocity.asArray(),
  54688. radius: collider._radius.asArray()
  54689. },
  54690. collisionId: collisionIndex,
  54691. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54692. maximumRetry: maximumRetry
  54693. };
  54694. var message = {
  54695. payload: payload,
  54696. taskType: WorkerTaskType.COLLIDE
  54697. };
  54698. this._worker.postMessage(message);
  54699. };
  54700. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54701. this._scene = scene;
  54702. this._scene.registerAfterRender(this._afterRender);
  54703. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54704. this._worker = new Worker(workerUrl);
  54705. this._worker.onmessage = this._onMessageFromWorker;
  54706. var message = {
  54707. payload: {},
  54708. taskType: WorkerTaskType.INIT
  54709. };
  54710. this._worker.postMessage(message);
  54711. };
  54712. CollisionCoordinatorWorker.prototype.destroy = function () {
  54713. this._scene.unregisterAfterRender(this._afterRender);
  54714. this._worker.terminate();
  54715. };
  54716. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54717. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54718. this.onMeshUpdated(mesh);
  54719. };
  54720. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54721. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54722. };
  54723. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54724. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54725. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54726. this.onGeometryUpdated(geometry);
  54727. };
  54728. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54729. this._toRemoveGeometryArray.push(geometry.id);
  54730. };
  54731. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54732. var submeshes = [];
  54733. if (mesh.subMeshes) {
  54734. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54735. var boundingInfo = sm.getBoundingInfo();
  54736. return {
  54737. position: idx,
  54738. verticesStart: sm.verticesStart,
  54739. verticesCount: sm.verticesCount,
  54740. indexStart: sm.indexStart,
  54741. indexCount: sm.indexCount,
  54742. hasMaterial: !!sm.getMaterial(),
  54743. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54744. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54745. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54746. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54747. };
  54748. });
  54749. }
  54750. var geometryId = null;
  54751. if (mesh instanceof BABYLON.Mesh) {
  54752. var geometry = mesh.geometry;
  54753. geometryId = geometry ? geometry.id : null;
  54754. }
  54755. else if (mesh instanceof BABYLON.InstancedMesh) {
  54756. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54757. geometryId = geometry ? geometry.id : null;
  54758. }
  54759. var boundingInfo = mesh.getBoundingInfo();
  54760. return {
  54761. uniqueId: mesh.uniqueId,
  54762. id: mesh.id,
  54763. name: mesh.name,
  54764. geometryId: geometryId,
  54765. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54766. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54767. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54768. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54769. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54770. subMeshes: submeshes,
  54771. checkCollisions: mesh.checkCollisions
  54772. };
  54773. };
  54774. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54775. return {
  54776. id: geometry.id,
  54777. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54778. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54779. indices: new Uint32Array(geometry.getIndices() || []),
  54780. };
  54781. };
  54782. return CollisionCoordinatorWorker;
  54783. }());
  54784. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54785. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54786. function CollisionCoordinatorLegacy() {
  54787. this._scaledPosition = BABYLON.Vector3.Zero();
  54788. this._scaledVelocity = BABYLON.Vector3.Zero();
  54789. this._finalPosition = BABYLON.Vector3.Zero();
  54790. }
  54791. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54792. position.divideToRef(collider._radius, this._scaledPosition);
  54793. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54794. collider.collidedMesh = null;
  54795. collider._retry = 0;
  54796. collider._initialVelocity = this._scaledVelocity;
  54797. collider._initialPosition = this._scaledPosition;
  54798. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54799. this._finalPosition.multiplyInPlace(collider._radius);
  54800. //run the callback
  54801. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54802. };
  54803. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54804. this._scene = scene;
  54805. };
  54806. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54807. //Legacy need no destruction method.
  54808. };
  54809. //No update in legacy mode
  54810. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54811. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54812. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54813. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54814. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54815. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54816. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54817. if (excludedMesh === void 0) { excludedMesh = null; }
  54818. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54819. if (collider._retry >= maximumRetry) {
  54820. finalPosition.copyFrom(position);
  54821. return;
  54822. }
  54823. // Check if this is a mesh else camera or -1
  54824. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54825. collider._initialize(position, velocity, closeDistance);
  54826. // Check all meshes
  54827. for (var index = 0; index < this._scene.meshes.length; index++) {
  54828. var mesh = this._scene.meshes[index];
  54829. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54830. mesh._checkCollision(collider);
  54831. }
  54832. }
  54833. if (!collider.collisionFound) {
  54834. position.addToRef(velocity, finalPosition);
  54835. return;
  54836. }
  54837. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54838. collider._getResponse(position, velocity);
  54839. }
  54840. if (velocity.length() <= closeDistance) {
  54841. finalPosition.copyFrom(position);
  54842. return;
  54843. }
  54844. collider._retry++;
  54845. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54846. };
  54847. return CollisionCoordinatorLegacy;
  54848. }());
  54849. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54850. })(BABYLON || (BABYLON = {}));
  54851. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54852. var BABYLON;
  54853. (function (BABYLON) {
  54854. /**
  54855. * A particle represents one of the element emitted by a particle system.
  54856. * This is mainly define by its coordinates, direction, velocity and age.
  54857. */
  54858. var Particle = /** @class */ (function () {
  54859. /**
  54860. * Creates a new instance Particle
  54861. * @param particleSystem the particle system the particle belongs to
  54862. */
  54863. function Particle(
  54864. /**
  54865. * particleSystem the particle system the particle belongs to.
  54866. */
  54867. particleSystem) {
  54868. this.particleSystem = particleSystem;
  54869. /**
  54870. * The world position of the particle in the scene.
  54871. */
  54872. this.position = BABYLON.Vector3.Zero();
  54873. /**
  54874. * The world direction of the particle in the scene.
  54875. */
  54876. this.direction = BABYLON.Vector3.Zero();
  54877. /**
  54878. * The color of the particle.
  54879. */
  54880. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54881. /**
  54882. * The color change of the particle per step.
  54883. */
  54884. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54885. /**
  54886. * Defines how long will the life of the particle be.
  54887. */
  54888. this.lifeTime = 1.0;
  54889. /**
  54890. * The current age of the particle.
  54891. */
  54892. this.age = 0;
  54893. /**
  54894. * The current size of the particle.
  54895. */
  54896. this.size = 0;
  54897. /**
  54898. * The current scale of the particle.
  54899. */
  54900. this.scale = new BABYLON.Vector2(1, 1);
  54901. /**
  54902. * The current angle of the particle.
  54903. */
  54904. this.angle = 0;
  54905. /**
  54906. * Defines how fast is the angle changing.
  54907. */
  54908. this.angularSpeed = 0;
  54909. /**
  54910. * Defines the cell index used by the particle to be rendered from a sprite.
  54911. */
  54912. this.cellIndex = 0;
  54913. /** @hidden */
  54914. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54915. /** @hidden */
  54916. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54917. /** @hidden */
  54918. this._currentSize1 = 0;
  54919. /** @hidden */
  54920. this._currentSize2 = 0;
  54921. /** @hidden */
  54922. this._currentAngularSpeed1 = 0;
  54923. /** @hidden */
  54924. this._currentAngularSpeed2 = 0;
  54925. /** @hidden */
  54926. this._currentVelocity1 = 0;
  54927. /** @hidden */
  54928. this._currentVelocity2 = 0;
  54929. if (!this.particleSystem.isAnimationSheetEnabled) {
  54930. return;
  54931. }
  54932. this.updateCellInfoFromSystem();
  54933. }
  54934. Particle.prototype.updateCellInfoFromSystem = function () {
  54935. this.cellIndex = this.particleSystem.startSpriteCellID;
  54936. };
  54937. /**
  54938. * Defines how the sprite cell index is updated for the particle
  54939. */
  54940. Particle.prototype.updateCellIndex = function () {
  54941. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54942. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54943. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54944. };
  54945. /**
  54946. * Copy the properties of particle to another one.
  54947. * @param other the particle to copy the information to.
  54948. */
  54949. Particle.prototype.copyTo = function (other) {
  54950. other.position.copyFrom(this.position);
  54951. if (this._initialDirection) {
  54952. if (other._initialDirection) {
  54953. other._initialDirection.copyFrom(this._initialDirection);
  54954. }
  54955. else {
  54956. other._initialDirection = this._initialDirection.clone();
  54957. }
  54958. }
  54959. else {
  54960. other._initialDirection = null;
  54961. }
  54962. other.direction.copyFrom(this.direction);
  54963. other.color.copyFrom(this.color);
  54964. other.colorStep.copyFrom(this.colorStep);
  54965. other.lifeTime = this.lifeTime;
  54966. other.age = this.age;
  54967. other.size = this.size;
  54968. other.scale.copyFrom(this.scale);
  54969. other.angle = this.angle;
  54970. other.angularSpeed = this.angularSpeed;
  54971. other.particleSystem = this.particleSystem;
  54972. other.cellIndex = this.cellIndex;
  54973. if (this._currentColorGradient) {
  54974. other._currentColorGradient = this._currentColorGradient;
  54975. other._currentColor1.copyFrom(this._currentColor1);
  54976. other._currentColor2.copyFrom(this._currentColor2);
  54977. }
  54978. if (this._currentSizeGradient) {
  54979. other._currentSizeGradient = this._currentSizeGradient;
  54980. other._currentSize1 = this._currentSize1;
  54981. other._currentSize2 = this._currentSize2;
  54982. }
  54983. if (this._currentAngularSpeedGradient) {
  54984. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54985. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54986. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54987. }
  54988. if (this._currentVelocityGradient) {
  54989. other._currentVelocityGradient = this._currentVelocityGradient;
  54990. other._currentVelocity1 = this._currentVelocity1;
  54991. other._currentVelocity2 = this._currentVelocity2;
  54992. }
  54993. if (this.particleSystem.isAnimationSheetEnabled) {
  54994. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54995. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54996. }
  54997. };
  54998. return Particle;
  54999. }());
  55000. BABYLON.Particle = Particle;
  55001. })(BABYLON || (BABYLON = {}));
  55002. //# sourceMappingURL=babylon.particle.js.map
  55003. var BABYLON;
  55004. (function (BABYLON) {
  55005. /**
  55006. * This represents a particle system in Babylon.
  55007. * 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.
  55008. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55009. * @example https://doc.babylonjs.com/babylon101/particles
  55010. */
  55011. var ParticleSystem = /** @class */ (function () {
  55012. /**
  55013. * Instantiates a particle system.
  55014. * 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.
  55015. * @param name The name of the particle system
  55016. * @param capacity The max number of particles alive at the same time
  55017. * @param scene The scene the particle system belongs to
  55018. * @param customEffect a custom effect used to change the way particles are rendered by default
  55019. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55020. * @param epsilon Offset used to render the particles
  55021. */
  55022. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55023. if (customEffect === void 0) { customEffect = null; }
  55024. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55025. if (epsilon === void 0) { epsilon = 0.01; }
  55026. var _this = this;
  55027. /**
  55028. * List of animations used by the particle system.
  55029. */
  55030. this.animations = [];
  55031. /**
  55032. * The rendering group used by the Particle system to chose when to render.
  55033. */
  55034. this.renderingGroupId = 0;
  55035. /**
  55036. * The emitter represents the Mesh or position we are attaching the particle system to.
  55037. */
  55038. this.emitter = null;
  55039. /**
  55040. * The maximum number of particles to emit per frame
  55041. */
  55042. this.emitRate = 10;
  55043. /**
  55044. * If you want to launch only a few particles at once, that can be done, as well.
  55045. */
  55046. this.manualEmitCount = -1;
  55047. /**
  55048. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55049. */
  55050. this.updateSpeed = 0.01;
  55051. /**
  55052. * The amount of time the particle system is running (depends of the overall update speed).
  55053. */
  55054. this.targetStopDuration = 0;
  55055. /**
  55056. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55057. */
  55058. this.disposeOnStop = false;
  55059. /**
  55060. * Minimum power of emitting particles.
  55061. */
  55062. this.minEmitPower = 1;
  55063. /**
  55064. * Maximum power of emitting particles.
  55065. */
  55066. this.maxEmitPower = 1;
  55067. /**
  55068. * Minimum life time of emitting particles.
  55069. */
  55070. this.minLifeTime = 1;
  55071. /**
  55072. * Maximum life time of emitting particles.
  55073. */
  55074. this.maxLifeTime = 1;
  55075. /**
  55076. * Minimum Size of emitting particles.
  55077. */
  55078. this.minSize = 1;
  55079. /**
  55080. * Maximum Size of emitting particles.
  55081. */
  55082. this.maxSize = 1;
  55083. /**
  55084. * Minimum scale of emitting particles on X axis.
  55085. */
  55086. this.minScaleX = 1;
  55087. /**
  55088. * Maximum scale of emitting particles on X axis.
  55089. */
  55090. this.maxScaleX = 1;
  55091. /**
  55092. * Minimum scale of emitting particles on Y axis.
  55093. */
  55094. this.minScaleY = 1;
  55095. /**
  55096. * Maximum scale of emitting particles on Y axis.
  55097. */
  55098. this.maxScaleY = 1;
  55099. /**
  55100. * Gets or sets the minimal initial rotation in radians.
  55101. */
  55102. this.minInitialRotation = 0;
  55103. /**
  55104. * Gets or sets the maximal initial rotation in radians.
  55105. */
  55106. this.maxInitialRotation = 0;
  55107. /**
  55108. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55109. */
  55110. this.minAngularSpeed = 0;
  55111. /**
  55112. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55113. */
  55114. this.maxAngularSpeed = 0;
  55115. /**
  55116. * The layer mask we are rendering the particles through.
  55117. */
  55118. this.layerMask = 0x0FFFFFFF;
  55119. /**
  55120. * This can help using your own shader to render the particle system.
  55121. * The according effect will be created
  55122. */
  55123. this.customShader = null;
  55124. /**
  55125. * By default particle system starts as soon as they are created. This prevents the
  55126. * automatic start to happen and let you decide when to start emitting particles.
  55127. */
  55128. this.preventAutoStart = false;
  55129. /**
  55130. * Callback triggered when the particle animation is ending.
  55131. */
  55132. this.onAnimationEnd = null;
  55133. /**
  55134. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55135. */
  55136. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55137. /**
  55138. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55139. * to override the particles.
  55140. */
  55141. this.forceDepthWrite = false;
  55142. /**
  55143. * You can use gravity if you want to give an orientation to your particles.
  55144. */
  55145. this.gravity = BABYLON.Vector3.Zero();
  55146. this._colorGradients = null;
  55147. this._sizeGradients = null;
  55148. this._lifeTimeGradients = null;
  55149. this._angularSpeedGradients = null;
  55150. this._velocityGradients = null;
  55151. /**
  55152. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55153. */
  55154. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55155. /**
  55156. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55157. */
  55158. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55159. /**
  55160. * Color the particle will have at the end of its lifetime
  55161. */
  55162. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55163. /**
  55164. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55165. */
  55166. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55167. /**
  55168. * 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)
  55169. */
  55170. this.spriteCellChangeSpeed = 1;
  55171. /**
  55172. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55173. */
  55174. this.startSpriteCellID = 0;
  55175. /**
  55176. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55177. */
  55178. this.endSpriteCellID = 0;
  55179. /**
  55180. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55181. */
  55182. this.spriteCellWidth = 0;
  55183. /**
  55184. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55185. */
  55186. this.spriteCellHeight = 0;
  55187. /** 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 */
  55188. this.preWarmCycles = 0;
  55189. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55190. this.preWarmStepOffset = 1;
  55191. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55192. this.translationPivot = new BABYLON.Vector2(0, 0);
  55193. /**
  55194. * An event triggered when the system is disposed
  55195. */
  55196. this.onDisposeObservable = new BABYLON.Observable();
  55197. /**
  55198. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55199. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55200. */
  55201. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55202. this._particles = new Array();
  55203. this._stockParticles = new Array();
  55204. this._newPartsExcess = 0;
  55205. this._vertexBuffers = {};
  55206. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55207. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55208. this._scaledDirection = BABYLON.Vector3.Zero();
  55209. this._scaledGravity = BABYLON.Vector3.Zero();
  55210. this._currentRenderId = -1;
  55211. this._useInstancing = false;
  55212. this._started = false;
  55213. this._stopped = false;
  55214. this._actualFrame = 0;
  55215. this._isBillboardBased = true;
  55216. // start of sub system methods
  55217. /**
  55218. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55219. * Its lifetime will start back at 0.
  55220. */
  55221. this.recycleParticle = function (particle) {
  55222. var lastParticle = _this._particles.pop();
  55223. if (lastParticle !== particle) {
  55224. lastParticle.copyTo(particle);
  55225. }
  55226. _this._stockParticles.push(lastParticle);
  55227. };
  55228. this._createParticle = function () {
  55229. var particle;
  55230. if (_this._stockParticles.length !== 0) {
  55231. particle = _this._stockParticles.pop();
  55232. particle.age = 0;
  55233. particle._currentColorGradient = null;
  55234. particle.cellIndex = _this.startSpriteCellID;
  55235. }
  55236. else {
  55237. particle = new BABYLON.Particle(_this);
  55238. }
  55239. return particle;
  55240. };
  55241. this._emitFromParticle = function (particle) {
  55242. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55243. return;
  55244. }
  55245. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55246. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55247. subSystem._rootParticleSystem = _this;
  55248. _this.activeSubSystems.push(subSystem);
  55249. subSystem.start();
  55250. };
  55251. this.id = name;
  55252. this.name = name;
  55253. this._capacity = capacity;
  55254. this._epsilon = epsilon;
  55255. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55256. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55257. this._customEffect = customEffect;
  55258. scene.particleSystems.push(this);
  55259. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55260. this._createIndexBuffer();
  55261. this._createVertexBuffers();
  55262. // Default emitter type
  55263. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55264. this.updateFunction = function (particles) {
  55265. var _loop_1 = function () {
  55266. particle = particles[index];
  55267. particle.age += _this._scaledUpdateSpeed;
  55268. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55269. _this._emitFromParticle(particle);
  55270. _this.recycleParticle(particle);
  55271. index--;
  55272. return "continue";
  55273. }
  55274. else {
  55275. var ratio = particle.age / particle.lifeTime;
  55276. // Color
  55277. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55278. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55279. if (currentGradient !== particle._currentColorGradient) {
  55280. particle._currentColor1.copyFrom(particle._currentColor2);
  55281. nextGradient.getColorToRef(particle._currentColor2);
  55282. particle._currentColorGradient = currentGradient;
  55283. }
  55284. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55285. });
  55286. }
  55287. else {
  55288. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55289. particle.color.addInPlace(_this._scaledColorStep);
  55290. if (particle.color.a < 0) {
  55291. particle.color.a = 0;
  55292. }
  55293. }
  55294. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55295. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55296. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55297. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55298. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55299. particle._currentAngularSpeedGradient = currentGradient;
  55300. }
  55301. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55302. });
  55303. }
  55304. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55305. var directionScale_1 = _this._scaledUpdateSpeed;
  55306. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55307. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55308. if (currentGradient !== particle._currentVelocityGradient) {
  55309. particle._currentVelocity1 = particle._currentVelocity2;
  55310. particle._currentVelocity2 = nextGradient.getFactor();
  55311. particle._currentVelocityGradient = currentGradient;
  55312. }
  55313. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55314. });
  55315. }
  55316. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55317. particle.position.addInPlace(_this._scaledDirection);
  55318. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55319. particle.direction.addInPlace(_this._scaledGravity);
  55320. // Size
  55321. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55322. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55323. if (currentGradient !== particle._currentSizeGradient) {
  55324. particle._currentSize1 = particle._currentSize2;
  55325. particle._currentSize2 = nextGradient.getFactor();
  55326. particle._currentSizeGradient = currentGradient;
  55327. }
  55328. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55329. });
  55330. }
  55331. if (_this._isAnimationSheetEnabled) {
  55332. particle.updateCellIndex();
  55333. }
  55334. }
  55335. };
  55336. var particle;
  55337. for (var index = 0; index < particles.length; index++) {
  55338. _loop_1();
  55339. }
  55340. };
  55341. }
  55342. /**
  55343. * Gets the current list of color gradients.
  55344. * You must use addColorGradient and removeColorGradient to udpate this list
  55345. * @returns the list of color gradients
  55346. */
  55347. ParticleSystem.prototype.getColorGradients = function () {
  55348. return this._colorGradients;
  55349. };
  55350. /**
  55351. * Gets the current list of size gradients.
  55352. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55353. * @returns the list of size gradients
  55354. */
  55355. ParticleSystem.prototype.getSizeGradients = function () {
  55356. return this._sizeGradients;
  55357. };
  55358. /**
  55359. * Gets the current list of life time gradients.
  55360. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55361. * @returns the list of life time gradients
  55362. */
  55363. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55364. return this._lifeTimeGradients;
  55365. };
  55366. /**
  55367. * Gets the current list of angular speed gradients.
  55368. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55369. * @returns the list of angular speed gradients
  55370. */
  55371. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55372. return this._angularSpeedGradients;
  55373. };
  55374. /**
  55375. * Gets the current list of velocity gradients.
  55376. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55377. * @returns the list of velocity gradients
  55378. */
  55379. ParticleSystem.prototype.getVelocityGradients = function () {
  55380. return this._velocityGradients;
  55381. };
  55382. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55383. /**
  55384. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55385. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55386. */
  55387. get: function () {
  55388. if (this.particleEmitterType.direction1) {
  55389. return this.particleEmitterType.direction1;
  55390. }
  55391. return BABYLON.Vector3.Zero();
  55392. },
  55393. set: function (value) {
  55394. if (this.particleEmitterType.direction1) {
  55395. this.particleEmitterType.direction1 = value;
  55396. }
  55397. },
  55398. enumerable: true,
  55399. configurable: true
  55400. });
  55401. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55402. /**
  55403. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55404. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55405. */
  55406. get: function () {
  55407. if (this.particleEmitterType.direction2) {
  55408. return this.particleEmitterType.direction2;
  55409. }
  55410. return BABYLON.Vector3.Zero();
  55411. },
  55412. set: function (value) {
  55413. if (this.particleEmitterType.direction2) {
  55414. this.particleEmitterType.direction2 = value;
  55415. }
  55416. },
  55417. enumerable: true,
  55418. configurable: true
  55419. });
  55420. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55421. /**
  55422. * 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.
  55423. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55424. */
  55425. get: function () {
  55426. if (this.particleEmitterType.minEmitBox) {
  55427. return this.particleEmitterType.minEmitBox;
  55428. }
  55429. return BABYLON.Vector3.Zero();
  55430. },
  55431. set: function (value) {
  55432. if (this.particleEmitterType.minEmitBox) {
  55433. this.particleEmitterType.minEmitBox = value;
  55434. }
  55435. },
  55436. enumerable: true,
  55437. configurable: true
  55438. });
  55439. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55440. /**
  55441. * 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.
  55442. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55443. */
  55444. get: function () {
  55445. if (this.particleEmitterType.maxEmitBox) {
  55446. return this.particleEmitterType.maxEmitBox;
  55447. }
  55448. return BABYLON.Vector3.Zero();
  55449. },
  55450. set: function (value) {
  55451. if (this.particleEmitterType.maxEmitBox) {
  55452. this.particleEmitterType.maxEmitBox = value;
  55453. }
  55454. },
  55455. enumerable: true,
  55456. configurable: true
  55457. });
  55458. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55459. /**
  55460. * Sets a callback that will be triggered when the system is disposed
  55461. */
  55462. set: function (callback) {
  55463. if (this._onDisposeObserver) {
  55464. this.onDisposeObservable.remove(this._onDisposeObserver);
  55465. }
  55466. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55467. },
  55468. enumerable: true,
  55469. configurable: true
  55470. });
  55471. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55472. /**
  55473. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55474. */
  55475. get: function () {
  55476. return this._isAnimationSheetEnabled;
  55477. },
  55478. enumerable: true,
  55479. configurable: true
  55480. });
  55481. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55482. /**
  55483. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55484. */
  55485. get: function () {
  55486. return this._isBillboardBased;
  55487. },
  55488. set: function (value) {
  55489. if (this._isBillboardBased === value) {
  55490. return;
  55491. }
  55492. this._isBillboardBased = value;
  55493. this._resetEffect();
  55494. },
  55495. enumerable: true,
  55496. configurable: true
  55497. });
  55498. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55499. //end of Sub-emitter
  55500. /**
  55501. * Gets the current list of active particles
  55502. */
  55503. get: function () {
  55504. return this._particles;
  55505. },
  55506. enumerable: true,
  55507. configurable: true
  55508. });
  55509. /**
  55510. * Returns the string "ParticleSystem"
  55511. * @returns a string containing the class name
  55512. */
  55513. ParticleSystem.prototype.getClassName = function () {
  55514. return "ParticleSystem";
  55515. };
  55516. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55517. var newGradient = new BABYLON.FactorGradient();
  55518. newGradient.gradient = gradient;
  55519. newGradient.factor1 = factor;
  55520. newGradient.factor2 = factor2;
  55521. factorGradients.push(newGradient);
  55522. factorGradients.sort(function (a, b) {
  55523. if (a.gradient < b.gradient) {
  55524. return -1;
  55525. }
  55526. else if (a.gradient > b.gradient) {
  55527. return 1;
  55528. }
  55529. return 0;
  55530. });
  55531. };
  55532. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55533. if (!factorGradients) {
  55534. return;
  55535. }
  55536. var index = 0;
  55537. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55538. var factorGradient = factorGradients_1[_i];
  55539. if (factorGradient.gradient === gradient) {
  55540. factorGradients.splice(index, 1);
  55541. break;
  55542. }
  55543. index++;
  55544. }
  55545. };
  55546. /**
  55547. * Adds a new life time gradient
  55548. * @param gradient defines the gradient to use (between 0 and 1)
  55549. * @param factor defines the life time factor to affect to the specified gradient
  55550. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55551. * @returns the current particle system
  55552. */
  55553. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55554. if (!this._lifeTimeGradients) {
  55555. this._lifeTimeGradients = [];
  55556. }
  55557. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55558. return this;
  55559. };
  55560. /**
  55561. * Remove a specific life time gradient
  55562. * @param gradient defines the gradient to remove
  55563. * @returns the current particle system
  55564. */
  55565. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55566. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55567. return this;
  55568. };
  55569. /**
  55570. * Adds a new size gradient
  55571. * @param gradient defines the gradient to use (between 0 and 1)
  55572. * @param factor defines the size factor to affect to the specified gradient
  55573. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55574. * @returns the current particle system
  55575. */
  55576. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55577. if (!this._sizeGradients) {
  55578. this._sizeGradients = [];
  55579. }
  55580. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55581. return this;
  55582. };
  55583. /**
  55584. * Remove a specific size gradient
  55585. * @param gradient defines the gradient to remove
  55586. * @returns the current particle system
  55587. */
  55588. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55589. this._removeFactorGradient(this._sizeGradients, gradient);
  55590. return this;
  55591. };
  55592. /**
  55593. * Adds a new angular speed gradient
  55594. * @param gradient defines the gradient to use (between 0 and 1)
  55595. * @param factor defines the size factor to affect to the specified gradient
  55596. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55597. * @returns the current particle system
  55598. */
  55599. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55600. if (!this._angularSpeedGradients) {
  55601. this._angularSpeedGradients = [];
  55602. }
  55603. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55604. return this;
  55605. };
  55606. /**
  55607. * Remove a specific angular speed gradient
  55608. * @param gradient defines the gradient to remove
  55609. * @returns the current particle system
  55610. */
  55611. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55612. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55613. return this;
  55614. };
  55615. /**
  55616. * Adds a new velocity gradient
  55617. * @param gradient defines the gradient to use (between 0 and 1)
  55618. * @param factor defines the size factor to affect to the specified gradient
  55619. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55620. * @returns the current particle system
  55621. */
  55622. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55623. if (!this._velocityGradients) {
  55624. this._velocityGradients = [];
  55625. }
  55626. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55627. return this;
  55628. };
  55629. /**
  55630. * Remove a specific velocity gradient
  55631. * @param gradient defines the gradient to remove
  55632. * @returns the current particle system
  55633. */
  55634. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55635. this._removeFactorGradient(this._velocityGradients, gradient);
  55636. return this;
  55637. };
  55638. /**
  55639. * Adds a new color gradient
  55640. * @param gradient defines the gradient to use (between 0 and 1)
  55641. * @param color defines the color to affect to the specified gradient
  55642. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55643. */
  55644. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55645. if (!this._colorGradients) {
  55646. this._colorGradients = [];
  55647. }
  55648. var colorGradient = new BABYLON.ColorGradient();
  55649. colorGradient.gradient = gradient;
  55650. colorGradient.color1 = color;
  55651. colorGradient.color2 = color2;
  55652. this._colorGradients.push(colorGradient);
  55653. this._colorGradients.sort(function (a, b) {
  55654. if (a.gradient < b.gradient) {
  55655. return -1;
  55656. }
  55657. else if (a.gradient > b.gradient) {
  55658. return 1;
  55659. }
  55660. return 0;
  55661. });
  55662. return this;
  55663. };
  55664. /**
  55665. * Remove a specific color gradient
  55666. * @param gradient defines the gradient to remove
  55667. */
  55668. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55669. if (!this._colorGradients) {
  55670. return this;
  55671. }
  55672. var index = 0;
  55673. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55674. var colorGradient = _a[_i];
  55675. if (colorGradient.gradient === gradient) {
  55676. this._colorGradients.splice(index, 1);
  55677. break;
  55678. }
  55679. index++;
  55680. }
  55681. return this;
  55682. };
  55683. ParticleSystem.prototype._resetEffect = function () {
  55684. if (this._vertexBuffer) {
  55685. this._vertexBuffer.dispose();
  55686. this._vertexBuffer = null;
  55687. }
  55688. if (this._spriteBuffer) {
  55689. this._spriteBuffer.dispose();
  55690. this._spriteBuffer = null;
  55691. }
  55692. this._createVertexBuffers();
  55693. };
  55694. ParticleSystem.prototype._createVertexBuffers = function () {
  55695. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55696. if (this._isAnimationSheetEnabled) {
  55697. this._vertexBufferSize += 1;
  55698. }
  55699. if (!this._isBillboardBased) {
  55700. this._vertexBufferSize += 3;
  55701. }
  55702. var engine = this._scene.getEngine();
  55703. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55704. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55705. var dataOffset = 0;
  55706. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55707. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55708. dataOffset += 3;
  55709. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55710. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55711. dataOffset += 4;
  55712. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55713. this._vertexBuffers["angle"] = options;
  55714. dataOffset += 1;
  55715. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55716. this._vertexBuffers["size"] = size;
  55717. dataOffset += 2;
  55718. if (this._isAnimationSheetEnabled) {
  55719. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55720. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55721. dataOffset += 1;
  55722. }
  55723. if (!this._isBillboardBased) {
  55724. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55725. this._vertexBuffers["direction"] = directionBuffer;
  55726. dataOffset += 3;
  55727. }
  55728. var offsets;
  55729. if (this._useInstancing) {
  55730. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55731. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55732. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55733. }
  55734. else {
  55735. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55736. dataOffset += 2;
  55737. }
  55738. this._vertexBuffers["offset"] = offsets;
  55739. };
  55740. ParticleSystem.prototype._createIndexBuffer = function () {
  55741. if (this._useInstancing) {
  55742. return;
  55743. }
  55744. var indices = [];
  55745. var index = 0;
  55746. for (var count = 0; count < this._capacity; count++) {
  55747. indices.push(index);
  55748. indices.push(index + 1);
  55749. indices.push(index + 2);
  55750. indices.push(index);
  55751. indices.push(index + 2);
  55752. indices.push(index + 3);
  55753. index += 4;
  55754. }
  55755. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55756. };
  55757. /**
  55758. * Gets the maximum number of particles active at the same time.
  55759. * @returns The max number of active particles.
  55760. */
  55761. ParticleSystem.prototype.getCapacity = function () {
  55762. return this._capacity;
  55763. };
  55764. /**
  55765. * Gets Wether there are still active particles in the system.
  55766. * @returns True if it is alive, otherwise false.
  55767. */
  55768. ParticleSystem.prototype.isAlive = function () {
  55769. return this._alive;
  55770. };
  55771. /**
  55772. * Gets Wether the system has been started.
  55773. * @returns True if it has been started, otherwise false.
  55774. */
  55775. ParticleSystem.prototype.isStarted = function () {
  55776. return this._started;
  55777. };
  55778. /**
  55779. * Starts the particle system and begins to emit.
  55780. */
  55781. ParticleSystem.prototype.start = function () {
  55782. this._started = true;
  55783. this._stopped = false;
  55784. this._actualFrame = 0;
  55785. if (this.subEmitters && this.subEmitters.length != 0) {
  55786. this.activeSubSystems = new Array();
  55787. }
  55788. if (this.preWarmCycles) {
  55789. for (var index = 0; index < this.preWarmCycles; index++) {
  55790. this.animate(true);
  55791. }
  55792. }
  55793. };
  55794. /**
  55795. * Stops the particle system.
  55796. * @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.
  55797. */
  55798. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55799. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55800. this._stopped = true;
  55801. if (stopSubEmitters) {
  55802. this._stopSubEmitters();
  55803. }
  55804. };
  55805. // animation sheet
  55806. /**
  55807. * Remove all active particles
  55808. */
  55809. ParticleSystem.prototype.reset = function () {
  55810. this._stockParticles = [];
  55811. this._particles = [];
  55812. };
  55813. /**
  55814. * @hidden (for internal use only)
  55815. */
  55816. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55817. var offset = index * this._vertexBufferSize;
  55818. this._vertexData[offset++] = particle.position.x;
  55819. this._vertexData[offset++] = particle.position.y;
  55820. this._vertexData[offset++] = particle.position.z;
  55821. this._vertexData[offset++] = particle.color.r;
  55822. this._vertexData[offset++] = particle.color.g;
  55823. this._vertexData[offset++] = particle.color.b;
  55824. this._vertexData[offset++] = particle.color.a;
  55825. this._vertexData[offset++] = particle.angle;
  55826. this._vertexData[offset++] = particle.scale.x * particle.size;
  55827. this._vertexData[offset++] = particle.scale.y * particle.size;
  55828. if (this._isAnimationSheetEnabled) {
  55829. this._vertexData[offset++] = particle.cellIndex;
  55830. }
  55831. if (!this._isBillboardBased) {
  55832. if (particle._initialDirection) {
  55833. this._vertexData[offset++] = particle._initialDirection.x;
  55834. this._vertexData[offset++] = particle._initialDirection.y;
  55835. this._vertexData[offset++] = particle._initialDirection.z;
  55836. }
  55837. else {
  55838. this._vertexData[offset++] = particle.direction.x;
  55839. this._vertexData[offset++] = particle.direction.y;
  55840. this._vertexData[offset++] = particle.direction.z;
  55841. }
  55842. }
  55843. if (!this._useInstancing) {
  55844. if (this._isAnimationSheetEnabled) {
  55845. if (offsetX === 0)
  55846. offsetX = this._epsilon;
  55847. else if (offsetX === 1)
  55848. offsetX = 1 - this._epsilon;
  55849. if (offsetY === 0)
  55850. offsetY = this._epsilon;
  55851. else if (offsetY === 1)
  55852. offsetY = 1 - this._epsilon;
  55853. }
  55854. this._vertexData[offset++] = offsetX;
  55855. this._vertexData[offset++] = offsetY;
  55856. }
  55857. };
  55858. ParticleSystem.prototype._stopSubEmitters = function () {
  55859. if (!this.activeSubSystems) {
  55860. return;
  55861. }
  55862. this.activeSubSystems.forEach(function (subSystem) {
  55863. subSystem.stop(true);
  55864. });
  55865. this.activeSubSystems = new Array();
  55866. };
  55867. ParticleSystem.prototype._removeFromRoot = function () {
  55868. if (!this._rootParticleSystem) {
  55869. return;
  55870. }
  55871. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55872. if (index !== -1) {
  55873. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55874. }
  55875. };
  55876. // End of sub system methods
  55877. ParticleSystem.prototype._update = function (newParticles) {
  55878. // Update current
  55879. this._alive = this._particles.length > 0;
  55880. this.updateFunction(this._particles);
  55881. // Add new ones
  55882. var worldMatrix;
  55883. if (this.emitter.position) {
  55884. var emitterMesh = this.emitter;
  55885. worldMatrix = emitterMesh.getWorldMatrix();
  55886. }
  55887. else {
  55888. var emitterPosition = this.emitter;
  55889. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55890. }
  55891. var particle;
  55892. var _loop_2 = function () {
  55893. if (this_1._particles.length === this_1._capacity) {
  55894. return "break";
  55895. }
  55896. particle = this_1._createParticle();
  55897. this_1._particles.push(particle);
  55898. // Emitter
  55899. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55900. if (this_1.startPositionFunction) {
  55901. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55902. }
  55903. else {
  55904. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55905. }
  55906. if (this_1.startDirectionFunction) {
  55907. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55908. }
  55909. else {
  55910. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55911. }
  55912. if (emitPower === 0) {
  55913. if (!particle._initialDirection) {
  55914. particle._initialDirection = particle.direction.clone();
  55915. }
  55916. else {
  55917. particle._initialDirection.copyFrom(particle.direction);
  55918. }
  55919. }
  55920. else {
  55921. particle._initialDirection = null;
  55922. }
  55923. particle.direction.scaleInPlace(emitPower);
  55924. // Life time
  55925. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55926. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55927. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55928. var factorGradient1 = currentGradient;
  55929. var factorGradient2 = nextGradient;
  55930. var lifeTime1 = factorGradient1.getFactor();
  55931. var lifeTime2 = factorGradient2.getFactor();
  55932. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55933. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55934. });
  55935. }
  55936. else {
  55937. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55938. }
  55939. // Size
  55940. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55941. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55942. }
  55943. else {
  55944. particle._currentSizeGradient = this_1._sizeGradients[0];
  55945. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55946. particle.size = particle._currentSize1;
  55947. if (this_1._sizeGradients.length > 1) {
  55948. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55949. }
  55950. else {
  55951. particle._currentSize2 = particle._currentSize1;
  55952. }
  55953. }
  55954. // Size and scale
  55955. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55956. // Angle
  55957. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55958. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55959. }
  55960. else {
  55961. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55962. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55963. particle._currentAngularSpeed1 = particle.angularSpeed;
  55964. if (this_1._angularSpeedGradients.length > 1) {
  55965. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55966. }
  55967. else {
  55968. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55969. }
  55970. }
  55971. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55972. // Velocity
  55973. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55974. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55975. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55976. if (this_1._velocityGradients.length > 1) {
  55977. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55978. }
  55979. else {
  55980. particle._currentVelocity2 = particle._currentVelocity1;
  55981. }
  55982. }
  55983. // Color
  55984. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55985. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55986. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55987. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55988. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55989. }
  55990. else {
  55991. particle._currentColorGradient = this_1._colorGradients[0];
  55992. particle._currentColorGradient.getColorToRef(particle.color);
  55993. particle._currentColor1.copyFrom(particle.color);
  55994. if (this_1._colorGradients.length > 1) {
  55995. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55996. }
  55997. else {
  55998. particle._currentColor2.copyFrom(particle.color);
  55999. }
  56000. }
  56001. // Sheet
  56002. if (this_1._isAnimationSheetEnabled) {
  56003. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56004. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56005. }
  56006. };
  56007. var this_1 = this, step;
  56008. for (var index = 0; index < newParticles; index++) {
  56009. var state_1 = _loop_2();
  56010. if (state_1 === "break")
  56011. break;
  56012. }
  56013. };
  56014. /** @hidden */
  56015. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56016. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56017. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56018. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56019. if (isAnimationSheetEnabled) {
  56020. attributeNamesOrOptions.push("cellIndex");
  56021. }
  56022. if (!isBillboardBased) {
  56023. attributeNamesOrOptions.push("direction");
  56024. }
  56025. return attributeNamesOrOptions;
  56026. };
  56027. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56028. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56029. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56030. if (isAnimationSheetEnabled) {
  56031. effectCreationOption.push("particlesInfos");
  56032. }
  56033. return effectCreationOption;
  56034. };
  56035. ParticleSystem.prototype._getEffect = function () {
  56036. if (this._customEffect) {
  56037. return this._customEffect;
  56038. }
  56039. ;
  56040. var defines = [];
  56041. if (this._scene.clipPlane) {
  56042. defines.push("#define CLIPPLANE");
  56043. }
  56044. if (this._isAnimationSheetEnabled) {
  56045. defines.push("#define ANIMATESHEET");
  56046. }
  56047. if (this._isBillboardBased) {
  56048. defines.push("#define BILLBOARD");
  56049. switch (this.billboardMode) {
  56050. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56051. defines.push("#define BILLBOARDY");
  56052. break;
  56053. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56054. default:
  56055. break;
  56056. }
  56057. }
  56058. // Effect
  56059. var join = defines.join("\n");
  56060. if (this._cachedDefines !== join) {
  56061. this._cachedDefines = join;
  56062. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56063. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56064. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56065. }
  56066. return this._effect;
  56067. };
  56068. /**
  56069. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56070. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56071. */
  56072. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56073. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56074. if (!this._started)
  56075. return;
  56076. if (!preWarmOnly) {
  56077. var effect = this._getEffect();
  56078. // Check
  56079. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56080. return;
  56081. if (this._currentRenderId === this._scene.getRenderId()) {
  56082. return;
  56083. }
  56084. this._currentRenderId = this._scene.getRenderId();
  56085. }
  56086. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56087. // determine the number of particles we need to create
  56088. var newParticles;
  56089. if (this.manualEmitCount > -1) {
  56090. newParticles = this.manualEmitCount;
  56091. this._newPartsExcess = 0;
  56092. this.manualEmitCount = 0;
  56093. }
  56094. else {
  56095. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56096. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56097. }
  56098. if (this._newPartsExcess > 1.0) {
  56099. newParticles += this._newPartsExcess >> 0;
  56100. this._newPartsExcess -= this._newPartsExcess >> 0;
  56101. }
  56102. this._alive = false;
  56103. if (!this._stopped) {
  56104. this._actualFrame += this._scaledUpdateSpeed;
  56105. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56106. this.stop();
  56107. }
  56108. else {
  56109. newParticles = 0;
  56110. }
  56111. this._update(newParticles);
  56112. // Stopped?
  56113. if (this._stopped) {
  56114. if (!this._alive) {
  56115. this._started = false;
  56116. if (this.onAnimationEnd) {
  56117. this.onAnimationEnd();
  56118. }
  56119. if (this.disposeOnStop) {
  56120. this._scene._toBeDisposed.push(this);
  56121. }
  56122. }
  56123. }
  56124. if (!preWarmOnly) {
  56125. // Update VBO
  56126. var offset = 0;
  56127. for (var index = 0; index < this._particles.length; index++) {
  56128. var particle = this._particles[index];
  56129. this._appendParticleVertices(offset, particle);
  56130. offset += this._useInstancing ? 1 : 4;
  56131. }
  56132. if (this._vertexBuffer) {
  56133. this._vertexBuffer.update(this._vertexData);
  56134. }
  56135. }
  56136. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56137. this.stop();
  56138. }
  56139. };
  56140. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56141. this._appendParticleVertex(offset++, particle, 0, 0);
  56142. if (!this._useInstancing) {
  56143. this._appendParticleVertex(offset++, particle, 1, 0);
  56144. this._appendParticleVertex(offset++, particle, 1, 1);
  56145. this._appendParticleVertex(offset++, particle, 0, 1);
  56146. }
  56147. };
  56148. /**
  56149. * Rebuilds the particle system.
  56150. */
  56151. ParticleSystem.prototype.rebuild = function () {
  56152. this._createIndexBuffer();
  56153. if (this._vertexBuffer) {
  56154. this._vertexBuffer._rebuild();
  56155. }
  56156. };
  56157. /**
  56158. * Is this system ready to be used/rendered
  56159. * @return true if the system is ready
  56160. */
  56161. ParticleSystem.prototype.isReady = function () {
  56162. var effect = this._getEffect();
  56163. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56164. return false;
  56165. }
  56166. return true;
  56167. };
  56168. /**
  56169. * Renders the particle system in its current state.
  56170. * @returns the current number of particles
  56171. */
  56172. ParticleSystem.prototype.render = function () {
  56173. var effect = this._getEffect();
  56174. // Check
  56175. if (!this.isReady() || !this._particles.length) {
  56176. return 0;
  56177. }
  56178. var engine = this._scene.getEngine();
  56179. // Render
  56180. engine.enableEffect(effect);
  56181. engine.setState(false);
  56182. var viewMatrix = this._scene.getViewMatrix();
  56183. effect.setTexture("diffuseSampler", this.particleTexture);
  56184. effect.setMatrix("view", viewMatrix);
  56185. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56186. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56187. var baseSize = this.particleTexture.getBaseSize();
  56188. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56189. }
  56190. effect.setVector2("translationPivot", this.translationPivot);
  56191. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56192. if (this._isBillboardBased) {
  56193. var camera = this._scene.activeCamera;
  56194. effect.setVector3("eyePosition", camera.globalPosition);
  56195. }
  56196. if (this._scene.clipPlane) {
  56197. var clipPlane = this._scene.clipPlane;
  56198. var invView = viewMatrix.clone();
  56199. invView.invert();
  56200. effect.setMatrix("invView", invView);
  56201. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56202. }
  56203. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56204. // Draw order
  56205. switch (this.blendMode) {
  56206. case ParticleSystem.BLENDMODE_ADD:
  56207. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56208. break;
  56209. case ParticleSystem.BLENDMODE_ONEONE:
  56210. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56211. break;
  56212. case ParticleSystem.BLENDMODE_STANDARD:
  56213. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56214. break;
  56215. }
  56216. if (this.forceDepthWrite) {
  56217. engine.setDepthWrite(true);
  56218. }
  56219. if (this._useInstancing) {
  56220. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56221. engine.unbindInstanceAttributes();
  56222. }
  56223. else {
  56224. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56225. }
  56226. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56227. return this._particles.length;
  56228. };
  56229. /**
  56230. * Disposes the particle system and free the associated resources
  56231. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56232. */
  56233. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56234. if (disposeTexture === void 0) { disposeTexture = true; }
  56235. if (this._vertexBuffer) {
  56236. this._vertexBuffer.dispose();
  56237. this._vertexBuffer = null;
  56238. }
  56239. if (this._spriteBuffer) {
  56240. this._spriteBuffer.dispose();
  56241. this._spriteBuffer = null;
  56242. }
  56243. if (this._indexBuffer) {
  56244. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56245. this._indexBuffer = null;
  56246. }
  56247. if (disposeTexture && this.particleTexture) {
  56248. this.particleTexture.dispose();
  56249. this.particleTexture = null;
  56250. }
  56251. this._removeFromRoot();
  56252. // Remove from scene
  56253. var index = this._scene.particleSystems.indexOf(this);
  56254. if (index > -1) {
  56255. this._scene.particleSystems.splice(index, 1);
  56256. }
  56257. // Callback
  56258. this.onDisposeObservable.notifyObservers(this);
  56259. this.onDisposeObservable.clear();
  56260. };
  56261. /**
  56262. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56263. * @param radius The radius of the sphere to emit from
  56264. * @returns the emitter
  56265. */
  56266. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56267. if (radius === void 0) { radius = 1; }
  56268. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56269. this.particleEmitterType = particleEmitter;
  56270. return particleEmitter;
  56271. };
  56272. /**
  56273. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56274. * @param radius The radius of the sphere to emit from
  56275. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56276. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56277. * @returns the emitter
  56278. */
  56279. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56280. if (radius === void 0) { radius = 1; }
  56281. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56282. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56283. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56284. this.particleEmitterType = particleEmitter;
  56285. return particleEmitter;
  56286. };
  56287. /**
  56288. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56289. * @param radius The radius of the cone to emit from
  56290. * @param angle The base angle of the cone
  56291. * @returns the emitter
  56292. */
  56293. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56294. if (radius === void 0) { radius = 1; }
  56295. if (angle === void 0) { angle = Math.PI / 4; }
  56296. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56297. this.particleEmitterType = particleEmitter;
  56298. return particleEmitter;
  56299. };
  56300. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56301. /**
  56302. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56303. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56304. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56305. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56306. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56307. * @returns the emitter
  56308. */
  56309. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56310. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56311. this.particleEmitterType = particleEmitter;
  56312. this.direction1 = direction1;
  56313. this.direction2 = direction2;
  56314. this.minEmitBox = minEmitBox;
  56315. this.maxEmitBox = maxEmitBox;
  56316. return particleEmitter;
  56317. };
  56318. // Clone
  56319. /**
  56320. * Clones the particle system.
  56321. * @param name The name of the cloned object
  56322. * @param newEmitter The new emitter to use
  56323. * @returns the cloned particle system
  56324. */
  56325. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56326. var custom = null;
  56327. var program = null;
  56328. if (this.customShader != null) {
  56329. program = this.customShader;
  56330. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56331. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56332. }
  56333. else if (this._customEffect) {
  56334. custom = this._customEffect;
  56335. }
  56336. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56337. result.customShader = program;
  56338. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56339. if (newEmitter === undefined) {
  56340. newEmitter = this.emitter;
  56341. }
  56342. result.emitter = newEmitter;
  56343. if (this.particleTexture) {
  56344. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56345. }
  56346. if (!this.preventAutoStart) {
  56347. result.start();
  56348. }
  56349. return result;
  56350. };
  56351. /**
  56352. * Serializes the particle system to a JSON object.
  56353. * @returns the JSON object
  56354. */
  56355. ParticleSystem.prototype.serialize = function () {
  56356. var serializationObject = {};
  56357. ParticleSystem._Serialize(serializationObject, this);
  56358. serializationObject.textureMask = this.textureMask.asArray();
  56359. serializationObject.customShader = this.customShader;
  56360. serializationObject.preventAutoStart = this.preventAutoStart;
  56361. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56362. return serializationObject;
  56363. };
  56364. /** @hidden */
  56365. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56366. serializationObject.name = particleSystem.name;
  56367. serializationObject.id = particleSystem.id;
  56368. serializationObject.capacity = particleSystem.getCapacity();
  56369. // Emitter
  56370. if (particleSystem.emitter.position) {
  56371. var emitterMesh = particleSystem.emitter;
  56372. serializationObject.emitterId = emitterMesh.id;
  56373. }
  56374. else {
  56375. var emitterPosition = particleSystem.emitter;
  56376. serializationObject.emitter = emitterPosition.asArray();
  56377. }
  56378. // Emitter
  56379. if (particleSystem.particleEmitterType) {
  56380. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56381. }
  56382. if (particleSystem.particleTexture) {
  56383. serializationObject.textureName = particleSystem.particleTexture.name;
  56384. }
  56385. // Animations
  56386. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56387. // Particle system
  56388. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56389. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56390. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56391. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56392. serializationObject.minSize = particleSystem.minSize;
  56393. serializationObject.maxSize = particleSystem.maxSize;
  56394. serializationObject.minScaleX = particleSystem.minScaleX;
  56395. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56396. serializationObject.minScaleY = particleSystem.minScaleY;
  56397. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56398. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56399. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56400. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56401. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56402. serializationObject.emitRate = particleSystem.emitRate;
  56403. serializationObject.gravity = particleSystem.gravity.asArray();
  56404. serializationObject.color1 = particleSystem.color1.asArray();
  56405. serializationObject.color2 = particleSystem.color2.asArray();
  56406. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56407. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56408. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56409. serializationObject.blendMode = particleSystem.blendMode;
  56410. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56411. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56412. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56413. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56414. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56415. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56416. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56417. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56418. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56419. var colorGradients = particleSystem.getColorGradients();
  56420. if (colorGradients) {
  56421. serializationObject.colorGradients = [];
  56422. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56423. var colorGradient = colorGradients_1[_i];
  56424. var serializedGradient = {
  56425. gradient: colorGradient.gradient,
  56426. color1: colorGradient.color1.asArray()
  56427. };
  56428. if (colorGradient.color2) {
  56429. serializedGradient.color2 = colorGradient.color2.asArray();
  56430. }
  56431. serializationObject.colorGradients.push(serializedGradient);
  56432. }
  56433. }
  56434. var sizeGradients = particleSystem.getSizeGradients();
  56435. if (sizeGradients) {
  56436. serializationObject.sizeGradients = [];
  56437. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56438. var sizeGradient = sizeGradients_1[_a];
  56439. var serializedGradient = {
  56440. gradient: sizeGradient.gradient,
  56441. factor1: sizeGradient.factor1
  56442. };
  56443. if (sizeGradient.factor2 !== undefined) {
  56444. serializedGradient.factor2 = sizeGradient.factor2;
  56445. }
  56446. serializationObject.sizeGradients.push(serializedGradient);
  56447. }
  56448. }
  56449. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56450. if (angularSpeedGradients) {
  56451. serializationObject.angularSpeedGradients = [];
  56452. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56453. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56454. var serializedGradient = {
  56455. gradient: angularSpeedGradient.gradient,
  56456. factor1: angularSpeedGradient.factor1
  56457. };
  56458. if (angularSpeedGradient.factor2 !== undefined) {
  56459. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56460. }
  56461. serializationObject.angularSpeedGradients.push(serializedGradient);
  56462. }
  56463. }
  56464. var velocityGradients = particleSystem.getVelocityGradients();
  56465. if (velocityGradients) {
  56466. serializationObject.velocityGradients = [];
  56467. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56468. var velocityGradient = velocityGradients_1[_c];
  56469. var serializedGradient = {
  56470. gradient: velocityGradient.gradient,
  56471. factor1: velocityGradient.factor1
  56472. };
  56473. if (velocityGradient.factor2 !== undefined) {
  56474. serializedGradient.factor2 = velocityGradient.factor2;
  56475. }
  56476. serializationObject.velocityGradients.push(serializedGradient);
  56477. }
  56478. }
  56479. };
  56480. /** @hidden */
  56481. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56482. // Texture
  56483. if (parsedParticleSystem.textureName) {
  56484. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56485. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56486. }
  56487. // Emitter
  56488. if (parsedParticleSystem.emitterId === undefined) {
  56489. particleSystem.emitter = BABYLON.Vector3.Zero();
  56490. }
  56491. else if (parsedParticleSystem.emitterId) {
  56492. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56493. }
  56494. else {
  56495. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56496. }
  56497. // Misc.
  56498. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56499. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56500. }
  56501. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56502. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56503. }
  56504. // Animations
  56505. if (parsedParticleSystem.animations) {
  56506. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56507. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56508. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56509. }
  56510. }
  56511. if (parsedParticleSystem.autoAnimate) {
  56512. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56513. }
  56514. // Particle system
  56515. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56516. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56517. particleSystem.minSize = parsedParticleSystem.minSize;
  56518. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56519. if (parsedParticleSystem.minScaleX) {
  56520. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56521. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56522. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56523. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56524. }
  56525. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56526. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56527. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56528. }
  56529. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56530. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56531. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56532. }
  56533. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56534. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56535. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56536. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56537. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56538. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56539. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56540. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56541. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56542. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56543. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56544. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56545. if (parsedParticleSystem.colorGradients) {
  56546. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56547. var colorGradient = _a[_i];
  56548. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56549. }
  56550. }
  56551. if (parsedParticleSystem.sizeGradients) {
  56552. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56553. var sizeGradient = _c[_b];
  56554. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56555. }
  56556. }
  56557. if (parsedParticleSystem.angularSpeedGradients) {
  56558. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56559. var angularSpeedGradient = _e[_d];
  56560. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56561. }
  56562. }
  56563. if (parsedParticleSystem.velocityGradients) {
  56564. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56565. var velocityGradient = _g[_f];
  56566. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56567. }
  56568. }
  56569. // Emitter
  56570. var emitterType;
  56571. if (parsedParticleSystem.particleEmitterType) {
  56572. switch (parsedParticleSystem.particleEmitterType.type) {
  56573. case "SphereParticleEmitter":
  56574. emitterType = new BABYLON.SphereParticleEmitter();
  56575. break;
  56576. case "SphereDirectedParticleEmitter":
  56577. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56578. break;
  56579. case "ConeEmitter":
  56580. case "ConeParticleEmitter":
  56581. emitterType = new BABYLON.ConeParticleEmitter();
  56582. break;
  56583. case "BoxEmitter":
  56584. case "BoxParticleEmitter":
  56585. default:
  56586. emitterType = new BABYLON.BoxParticleEmitter();
  56587. break;
  56588. }
  56589. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56590. }
  56591. else {
  56592. emitterType = new BABYLON.BoxParticleEmitter();
  56593. emitterType.parse(parsedParticleSystem);
  56594. }
  56595. particleSystem.particleEmitterType = emitterType;
  56596. // Animation sheet
  56597. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56598. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56599. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56600. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56601. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56602. };
  56603. /**
  56604. * Parses a JSON object to create a particle system.
  56605. * @param parsedParticleSystem The JSON object to parse
  56606. * @param scene The scene to create the particle system in
  56607. * @param rootUrl The root url to use to load external dependencies like texture
  56608. * @returns the Parsed particle system
  56609. */
  56610. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56611. var name = parsedParticleSystem.name;
  56612. var custom = null;
  56613. var program = null;
  56614. if (parsedParticleSystem.customShader) {
  56615. program = parsedParticleSystem.customShader;
  56616. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56617. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56618. }
  56619. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56620. particleSystem.customShader = program;
  56621. if (parsedParticleSystem.id) {
  56622. particleSystem.id = parsedParticleSystem.id;
  56623. }
  56624. // Auto start
  56625. if (parsedParticleSystem.preventAutoStart) {
  56626. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56627. }
  56628. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56629. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56630. if (!particleSystem.preventAutoStart) {
  56631. particleSystem.start();
  56632. }
  56633. return particleSystem;
  56634. };
  56635. /**
  56636. * Source color is added to the destination color without alpha affecting the result.
  56637. */
  56638. ParticleSystem.BLENDMODE_ONEONE = 0;
  56639. /**
  56640. * Blend current color and particle color using particle’s alpha.
  56641. */
  56642. ParticleSystem.BLENDMODE_STANDARD = 1;
  56643. /**
  56644. * Add current color and particle color multiplied by particle’s alpha.
  56645. */
  56646. ParticleSystem.BLENDMODE_ADD = 2;
  56647. return ParticleSystem;
  56648. }());
  56649. BABYLON.ParticleSystem = ParticleSystem;
  56650. })(BABYLON || (BABYLON = {}));
  56651. //# sourceMappingURL=babylon.particleSystem.js.map
  56652. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56653. var BABYLON;
  56654. (function (BABYLON) {
  56655. /**
  56656. * Particle emitter emitting particles from the inside of a box.
  56657. * It emits the particles randomly between 2 given directions.
  56658. */
  56659. var BoxParticleEmitter = /** @class */ (function () {
  56660. /**
  56661. * Creates a new instance BoxParticleEmitter
  56662. */
  56663. function BoxParticleEmitter() {
  56664. /**
  56665. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56666. */
  56667. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56668. /**
  56669. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56670. */
  56671. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56672. /**
  56673. * 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.
  56674. */
  56675. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56676. /**
  56677. * 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.
  56678. */
  56679. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56680. }
  56681. /**
  56682. * Called by the particle System when the direction is computed for the created particle.
  56683. * @param worldMatrix is the world matrix of the particle system
  56684. * @param directionToUpdate is the direction vector to update with the result
  56685. * @param particle is the particle we are computed the direction for
  56686. */
  56687. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56688. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56689. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56690. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56691. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56692. };
  56693. /**
  56694. * Called by the particle System when the position is computed for the created particle.
  56695. * @param worldMatrix is the world matrix of the particle system
  56696. * @param positionToUpdate is the position vector to update with the result
  56697. * @param particle is the particle we are computed the position for
  56698. */
  56699. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56700. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56701. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56702. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56704. };
  56705. /**
  56706. * Clones the current emitter and returns a copy of it
  56707. * @returns the new emitter
  56708. */
  56709. BoxParticleEmitter.prototype.clone = function () {
  56710. var newOne = new BoxParticleEmitter();
  56711. BABYLON.Tools.DeepCopy(this, newOne);
  56712. return newOne;
  56713. };
  56714. /**
  56715. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56716. * @param effect defines the update shader
  56717. */
  56718. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56719. effect.setVector3("direction1", this.direction1);
  56720. effect.setVector3("direction2", this.direction2);
  56721. effect.setVector3("minEmitBox", this.minEmitBox);
  56722. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56723. };
  56724. /**
  56725. * Returns a string to use to update the GPU particles update shader
  56726. * @returns a string containng the defines string
  56727. */
  56728. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56729. return "#define BOXEMITTER";
  56730. };
  56731. /**
  56732. * Returns the string "BoxParticleEmitter"
  56733. * @returns a string containing the class name
  56734. */
  56735. BoxParticleEmitter.prototype.getClassName = function () {
  56736. return "BoxParticleEmitter";
  56737. };
  56738. /**
  56739. * Serializes the particle system to a JSON object.
  56740. * @returns the JSON object
  56741. */
  56742. BoxParticleEmitter.prototype.serialize = function () {
  56743. var serializationObject = {};
  56744. serializationObject.type = this.getClassName();
  56745. serializationObject.direction1 = this.direction1.asArray();
  56746. serializationObject.direction2 = this.direction2.asArray();
  56747. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56748. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56749. return serializationObject;
  56750. };
  56751. /**
  56752. * Parse properties from a JSON object
  56753. * @param serializationObject defines the JSON object
  56754. */
  56755. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56756. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56757. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56758. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56759. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56760. };
  56761. return BoxParticleEmitter;
  56762. }());
  56763. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56764. })(BABYLON || (BABYLON = {}));
  56765. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56766. var BABYLON;
  56767. (function (BABYLON) {
  56768. /**
  56769. * Particle emitter emitting particles from the inside of a cone.
  56770. * It emits the particles alongside the cone volume from the base to the particle.
  56771. * The emission direction might be randomized.
  56772. */
  56773. var ConeParticleEmitter = /** @class */ (function () {
  56774. /**
  56775. * Creates a new instance ConeParticleEmitter
  56776. * @param radius the radius of the emission cone (1 by default)
  56777. * @param angles the cone base angle (PI by default)
  56778. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56779. */
  56780. function ConeParticleEmitter(radius, angle,
  56781. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56782. directionRandomizer) {
  56783. if (radius === void 0) { radius = 1; }
  56784. if (angle === void 0) { angle = Math.PI; }
  56785. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56786. this.directionRandomizer = directionRandomizer;
  56787. /**
  56788. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56789. */
  56790. this.radiusRange = 1;
  56791. /**
  56792. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56793. */
  56794. this.heightRange = 1;
  56795. this.angle = angle;
  56796. this.radius = radius;
  56797. }
  56798. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56799. /**
  56800. * Gets or sets the radius of the emission cone
  56801. */
  56802. get: function () {
  56803. return this._radius;
  56804. },
  56805. set: function (value) {
  56806. this._radius = value;
  56807. this._buildHeight();
  56808. },
  56809. enumerable: true,
  56810. configurable: true
  56811. });
  56812. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56813. /**
  56814. * Gets or sets the angle of the emission cone
  56815. */
  56816. get: function () {
  56817. return this._angle;
  56818. },
  56819. set: function (value) {
  56820. this._angle = value;
  56821. this._buildHeight();
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. ConeParticleEmitter.prototype._buildHeight = function () {
  56827. if (this._angle !== 0) {
  56828. this._height = this._radius / Math.tan(this._angle / 2);
  56829. }
  56830. else {
  56831. this._height = 1;
  56832. }
  56833. };
  56834. /**
  56835. * Called by the particle System when the direction is computed for the created particle.
  56836. * @param worldMatrix is the world matrix of the particle system
  56837. * @param directionToUpdate is the direction vector to update with the result
  56838. * @param particle is the particle we are computed the direction for
  56839. */
  56840. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56841. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56842. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56843. }
  56844. else {
  56845. // measure the direction Vector from the emitter to the particle.
  56846. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56847. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56848. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56849. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56850. direction.x += randX;
  56851. direction.y += randY;
  56852. direction.z += randZ;
  56853. direction.normalize();
  56854. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56855. }
  56856. };
  56857. /**
  56858. * Called by the particle System when the position is computed for the created particle.
  56859. * @param worldMatrix is the world matrix of the particle system
  56860. * @param positionToUpdate is the position vector to update with the result
  56861. * @param particle is the particle we are computed the position for
  56862. */
  56863. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56864. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56865. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56866. // Better distribution in a cone at normal angles.
  56867. h = 1 - h * h;
  56868. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56869. radius = radius * h;
  56870. var randX = radius * Math.sin(s);
  56871. var randZ = radius * Math.cos(s);
  56872. var randY = h * this._height;
  56873. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56874. };
  56875. /**
  56876. * Clones the current emitter and returns a copy of it
  56877. * @returns the new emitter
  56878. */
  56879. ConeParticleEmitter.prototype.clone = function () {
  56880. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56881. BABYLON.Tools.DeepCopy(this, newOne);
  56882. return newOne;
  56883. };
  56884. /**
  56885. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56886. * @param effect defines the update shader
  56887. */
  56888. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56889. effect.setFloat2("radius", this._radius, this.radiusRange);
  56890. effect.setFloat("coneAngle", this._angle);
  56891. effect.setFloat2("height", this._height, this.heightRange);
  56892. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56893. };
  56894. /**
  56895. * Returns a string to use to update the GPU particles update shader
  56896. * @returns a string containng the defines string
  56897. */
  56898. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56899. return "#define CONEEMITTER";
  56900. };
  56901. /**
  56902. * Returns the string "ConeParticleEmitter"
  56903. * @returns a string containing the class name
  56904. */
  56905. ConeParticleEmitter.prototype.getClassName = function () {
  56906. return "ConeParticleEmitter";
  56907. };
  56908. /**
  56909. * Serializes the particle system to a JSON object.
  56910. * @returns the JSON object
  56911. */
  56912. ConeParticleEmitter.prototype.serialize = function () {
  56913. var serializationObject = {};
  56914. serializationObject.type = this.getClassName();
  56915. serializationObject.radius = this._radius;
  56916. serializationObject.angle = this._angle;
  56917. serializationObject.directionRandomizer = this.directionRandomizer;
  56918. return serializationObject;
  56919. };
  56920. /**
  56921. * Parse properties from a JSON object
  56922. * @param serializationObject defines the JSON object
  56923. */
  56924. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56925. this.radius = serializationObject.radius;
  56926. this.angle = serializationObject.angle;
  56927. this.directionRandomizer = serializationObject.directionRandomizer;
  56928. };
  56929. return ConeParticleEmitter;
  56930. }());
  56931. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56932. })(BABYLON || (BABYLON = {}));
  56933. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56934. var BABYLON;
  56935. (function (BABYLON) {
  56936. /**
  56937. * Particle emitter emitting particles from the inside of a sphere.
  56938. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56939. */
  56940. var SphereParticleEmitter = /** @class */ (function () {
  56941. /**
  56942. * Creates a new instance SphereParticleEmitter
  56943. * @param radius the radius of the emission sphere (1 by default)
  56944. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56945. */
  56946. function SphereParticleEmitter(
  56947. /**
  56948. * The radius of the emission sphere.
  56949. */
  56950. radius,
  56951. /**
  56952. * How much to randomize the particle direction [0-1].
  56953. */
  56954. directionRandomizer) {
  56955. if (radius === void 0) { radius = 1; }
  56956. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56957. this.radius = radius;
  56958. this.directionRandomizer = directionRandomizer;
  56959. /**
  56960. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56961. */
  56962. this.radiusRange = 1;
  56963. }
  56964. /**
  56965. * Called by the particle System when the direction is computed for the created particle.
  56966. * @param worldMatrix is the world matrix of the particle system
  56967. * @param directionToUpdate is the direction vector to update with the result
  56968. * @param particle is the particle we are computed the direction for
  56969. */
  56970. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56971. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56972. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56973. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56974. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56975. direction.x += randX;
  56976. direction.y += randY;
  56977. direction.z += randZ;
  56978. direction.normalize();
  56979. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56980. };
  56981. /**
  56982. * Called by the particle System when the position is computed for the created particle.
  56983. * @param worldMatrix is the world matrix of the particle system
  56984. * @param positionToUpdate is the position vector to update with the result
  56985. * @param particle is the particle we are computed the position for
  56986. */
  56987. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56988. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56989. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56990. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56991. var theta = Math.acos(2 * v - 1);
  56992. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56993. var randY = randRadius * Math.cos(theta);
  56994. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56995. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56996. };
  56997. /**
  56998. * Clones the current emitter and returns a copy of it
  56999. * @returns the new emitter
  57000. */
  57001. SphereParticleEmitter.prototype.clone = function () {
  57002. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57003. BABYLON.Tools.DeepCopy(this, newOne);
  57004. return newOne;
  57005. };
  57006. /**
  57007. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57008. * @param effect defines the update shader
  57009. */
  57010. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57011. effect.setFloat("radius", this.radius);
  57012. effect.setFloat("radiusRange", this.radiusRange);
  57013. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57014. };
  57015. /**
  57016. * Returns a string to use to update the GPU particles update shader
  57017. * @returns a string containng the defines string
  57018. */
  57019. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57020. return "#define SPHEREEMITTER";
  57021. };
  57022. /**
  57023. * Returns the string "SphereParticleEmitter"
  57024. * @returns a string containing the class name
  57025. */
  57026. SphereParticleEmitter.prototype.getClassName = function () {
  57027. return "SphereParticleEmitter";
  57028. };
  57029. /**
  57030. * Serializes the particle system to a JSON object.
  57031. * @returns the JSON object
  57032. */
  57033. SphereParticleEmitter.prototype.serialize = function () {
  57034. var serializationObject = {};
  57035. serializationObject.type = this.getClassName();
  57036. serializationObject.radius = this.radius;
  57037. serializationObject.radiusRange = this.radiusRange;
  57038. serializationObject.directionRandomizer = this.directionRandomizer;
  57039. return serializationObject;
  57040. };
  57041. /**
  57042. * Parse properties from a JSON object
  57043. * @param serializationObject defines the JSON object
  57044. */
  57045. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57046. this.radius = serializationObject.radius;
  57047. this.radiusRange = serializationObject.radiusRange;
  57048. this.directionRandomizer = serializationObject.directionRandomizer;
  57049. };
  57050. return SphereParticleEmitter;
  57051. }());
  57052. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57053. /**
  57054. * Particle emitter emitting particles from the inside of a sphere.
  57055. * It emits the particles randomly between two vectors.
  57056. */
  57057. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57058. __extends(SphereDirectedParticleEmitter, _super);
  57059. /**
  57060. * Creates a new instance SphereDirectedParticleEmitter
  57061. * @param radius the radius of the emission sphere (1 by default)
  57062. * @param direction1 the min limit of the emission direction (up vector by default)
  57063. * @param direction2 the max limit of the emission direction (up vector by default)
  57064. */
  57065. function SphereDirectedParticleEmitter(radius,
  57066. /**
  57067. * The min limit of the emission direction.
  57068. */
  57069. direction1,
  57070. /**
  57071. * The max limit of the emission direction.
  57072. */
  57073. direction2) {
  57074. if (radius === void 0) { radius = 1; }
  57075. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57076. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57077. var _this = _super.call(this, radius) || this;
  57078. _this.direction1 = direction1;
  57079. _this.direction2 = direction2;
  57080. return _this;
  57081. }
  57082. /**
  57083. * Called by the particle System when the direction is computed for the created particle.
  57084. * @param worldMatrix is the world matrix of the particle system
  57085. * @param directionToUpdate is the direction vector to update with the result
  57086. * @param particle is the particle we are computed the direction for
  57087. */
  57088. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57089. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57090. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57091. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57092. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57093. };
  57094. /**
  57095. * Clones the current emitter and returns a copy of it
  57096. * @returns the new emitter
  57097. */
  57098. SphereDirectedParticleEmitter.prototype.clone = function () {
  57099. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57100. BABYLON.Tools.DeepCopy(this, newOne);
  57101. return newOne;
  57102. };
  57103. /**
  57104. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57105. * @param effect defines the update shader
  57106. */
  57107. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57108. effect.setFloat("radius", this.radius);
  57109. effect.setFloat("radiusRange", this.radiusRange);
  57110. effect.setVector3("direction1", this.direction1);
  57111. effect.setVector3("direction2", this.direction2);
  57112. };
  57113. /**
  57114. * Returns a string to use to update the GPU particles update shader
  57115. * @returns a string containng the defines string
  57116. */
  57117. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57118. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57119. };
  57120. /**
  57121. * Returns the string "SphereDirectedParticleEmitter"
  57122. * @returns a string containing the class name
  57123. */
  57124. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57125. return "SphereDirectedParticleEmitter";
  57126. };
  57127. /**
  57128. * Serializes the particle system to a JSON object.
  57129. * @returns the JSON object
  57130. */
  57131. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57132. var serializationObject = _super.prototype.serialize.call(this);
  57133. serializationObject.direction1 = this.direction1.asArray();
  57134. serializationObject.direction2 = this.direction2.asArray();
  57135. return serializationObject;
  57136. };
  57137. /**
  57138. * Parse properties from a JSON object
  57139. * @param serializationObject defines the JSON object
  57140. */
  57141. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57142. _super.prototype.parse.call(this, serializationObject);
  57143. this.direction1.copyFrom(serializationObject.direction1);
  57144. this.direction2.copyFrom(serializationObject.direction2);
  57145. };
  57146. return SphereDirectedParticleEmitter;
  57147. }(SphereParticleEmitter));
  57148. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57149. })(BABYLON || (BABYLON = {}));
  57150. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57151. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57152. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57153. s = arguments[i];
  57154. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57155. t[p] = s[p];
  57156. }
  57157. return t;
  57158. };
  57159. var BABYLON;
  57160. (function (BABYLON) {
  57161. /**
  57162. * This represents a GPU particle system in Babylon
  57163. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57164. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57165. */
  57166. var GPUParticleSystem = /** @class */ (function () {
  57167. /**
  57168. * Instantiates a GPU particle system.
  57169. * 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.
  57170. * @param name The name of the particle system
  57171. * @param options The options used to create the system
  57172. * @param scene The scene the particle system belongs to
  57173. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57174. */
  57175. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57176. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57177. /**
  57178. * The emitter represents the Mesh or position we are attaching the particle system to.
  57179. */
  57180. this.emitter = null;
  57181. /**
  57182. * The rendering group used by the Particle system to chose when to render.
  57183. */
  57184. this.renderingGroupId = 0;
  57185. /**
  57186. * The layer mask we are rendering the particles through.
  57187. */
  57188. this.layerMask = 0x0FFFFFFF;
  57189. this._accumulatedCount = 0;
  57190. this._targetIndex = 0;
  57191. this._currentRenderId = -1;
  57192. this._started = false;
  57193. this._stopped = false;
  57194. this._timeDelta = 0;
  57195. this._attributesStrideSize = 21;
  57196. this._actualFrame = 0;
  57197. this._rawTextureWidth = 256;
  57198. /**
  57199. * List of animations used by the particle system.
  57200. */
  57201. this.animations = [];
  57202. /**
  57203. * An event triggered when the system is disposed.
  57204. */
  57205. this.onDisposeObservable = new BABYLON.Observable();
  57206. /**
  57207. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57208. */
  57209. this.updateSpeed = 0.01;
  57210. /**
  57211. * The amount of time the particle system is running (depends of the overall update speed).
  57212. */
  57213. this.targetStopDuration = 0;
  57214. /**
  57215. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57216. */
  57217. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57218. /**
  57219. * Minimum life time of emitting particles.
  57220. */
  57221. this.minLifeTime = 1;
  57222. /**
  57223. * Maximum life time of emitting particles.
  57224. */
  57225. this.maxLifeTime = 1;
  57226. /**
  57227. * Minimum Size of emitting particles.
  57228. */
  57229. this.minSize = 1;
  57230. /**
  57231. * Maximum Size of emitting particles.
  57232. */
  57233. this.maxSize = 1;
  57234. /**
  57235. * Minimum scale of emitting particles on X axis.
  57236. */
  57237. this.minScaleX = 1;
  57238. /**
  57239. * Maximum scale of emitting particles on X axis.
  57240. */
  57241. this.maxScaleX = 1;
  57242. /**
  57243. * Minimum scale of emitting particles on Y axis.
  57244. */
  57245. this.minScaleY = 1;
  57246. /**
  57247. * Maximum scale of emitting particles on Y axis.
  57248. */
  57249. this.maxScaleY = 1;
  57250. /**
  57251. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57252. */
  57253. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57254. /**
  57255. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57256. */
  57257. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57258. /**
  57259. * Color the particle will have at the end of its lifetime.
  57260. */
  57261. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57262. /**
  57263. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57264. */
  57265. this.emitRate = 100;
  57266. /**
  57267. * You can use gravity if you want to give an orientation to your particles.
  57268. */
  57269. this.gravity = BABYLON.Vector3.Zero();
  57270. /**
  57271. * Minimum power of emitting particles.
  57272. */
  57273. this.minEmitPower = 1;
  57274. /**
  57275. * Maximum power of emitting particles.
  57276. */
  57277. this.maxEmitPower = 1;
  57278. /**
  57279. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57280. */
  57281. this.minAngularSpeed = 0;
  57282. /**
  57283. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57284. */
  57285. this.maxAngularSpeed = 0;
  57286. /**
  57287. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57288. * to override the particles.
  57289. */
  57290. this.forceDepthWrite = false;
  57291. this._preWarmDone = false;
  57292. /** 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 */
  57293. this.preWarmCycles = 0;
  57294. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57295. this.preWarmStepOffset = 1;
  57296. /**
  57297. * Gets or sets the minimal initial rotation in radians.
  57298. */
  57299. this.minInitialRotation = 0;
  57300. /**
  57301. * Gets or sets the maximal initial rotation in radians.
  57302. */
  57303. this.maxInitialRotation = 0;
  57304. /**
  57305. * 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)
  57306. */
  57307. this.spriteCellChangeSpeed = 1;
  57308. /**
  57309. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57310. */
  57311. this.startSpriteCellID = 0;
  57312. /**
  57313. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57314. */
  57315. this.endSpriteCellID = 0;
  57316. /**
  57317. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57318. */
  57319. this.spriteCellWidth = 0;
  57320. /**
  57321. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57322. */
  57323. this.spriteCellHeight = 0;
  57324. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57325. this.translationPivot = new BABYLON.Vector2(0, 0);
  57326. /**
  57327. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57328. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57329. */
  57330. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57331. this._isBillboardBased = true;
  57332. this._colorGradients = null;
  57333. this._angularSpeedGradients = null;
  57334. this._sizeGradients = null;
  57335. this._velocityGradients = null;
  57336. this.id = name;
  57337. this.name = name;
  57338. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57339. this._engine = this._scene.getEngine();
  57340. if (!options.randomTextureSize) {
  57341. delete options.randomTextureSize;
  57342. }
  57343. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57344. var optionsAsNumber = options;
  57345. if (isFinite(optionsAsNumber)) {
  57346. fullOptions.capacity = optionsAsNumber;
  57347. }
  57348. this._capacity = fullOptions.capacity;
  57349. this._activeCount = fullOptions.capacity;
  57350. this._currentActiveCount = 0;
  57351. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57352. this._scene.particleSystems.push(this);
  57353. this._updateEffectOptions = {
  57354. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57355. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57356. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57357. "angleRange", "radiusRange", "cellInfos"],
  57358. uniformBuffersNames: [],
  57359. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  57360. defines: "",
  57361. fallbacks: null,
  57362. onCompiled: null,
  57363. onError: null,
  57364. indexParameters: null,
  57365. maxSimultaneousLights: 0,
  57366. transformFeedbackVaryings: []
  57367. };
  57368. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57369. // Random data
  57370. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57371. var d = [];
  57372. for (var i = 0; i < maxTextureSize; ++i) {
  57373. d.push(Math.random());
  57374. d.push(Math.random());
  57375. d.push(Math.random());
  57376. d.push(Math.random());
  57377. }
  57378. 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);
  57379. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57380. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57381. d = [];
  57382. for (var i = 0; i < maxTextureSize; ++i) {
  57383. d.push(Math.random());
  57384. d.push(Math.random());
  57385. d.push(Math.random());
  57386. d.push(Math.random());
  57387. }
  57388. 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);
  57389. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57390. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57391. this._randomTextureSize = maxTextureSize;
  57392. }
  57393. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57394. /**
  57395. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57396. */
  57397. get: function () {
  57398. if (!BABYLON.Engine.LastCreatedEngine) {
  57399. return false;
  57400. }
  57401. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57402. },
  57403. enumerable: true,
  57404. configurable: true
  57405. });
  57406. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57407. /**
  57408. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57409. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57410. */
  57411. get: function () {
  57412. if (this.particleEmitterType.direction1) {
  57413. return this.particleEmitterType.direction1;
  57414. }
  57415. return BABYLON.Vector3.Zero();
  57416. },
  57417. set: function (value) {
  57418. if (this.particleEmitterType.direction1) {
  57419. this.particleEmitterType.direction1 = value;
  57420. }
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57426. /**
  57427. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57428. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57429. */
  57430. get: function () {
  57431. if (this.particleEmitterType.direction2) {
  57432. return this.particleEmitterType.direction2;
  57433. }
  57434. return BABYLON.Vector3.Zero();
  57435. },
  57436. set: function (value) {
  57437. if (this.particleEmitterType.direction2) {
  57438. this.particleEmitterType.direction2 = value;
  57439. }
  57440. },
  57441. enumerable: true,
  57442. configurable: true
  57443. });
  57444. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57445. /**
  57446. * 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.
  57447. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57448. */
  57449. get: function () {
  57450. if (this.particleEmitterType.minEmitBox) {
  57451. return this.particleEmitterType.minEmitBox;
  57452. }
  57453. return BABYLON.Vector3.Zero();
  57454. },
  57455. set: function (value) {
  57456. if (this.particleEmitterType.minEmitBox) {
  57457. this.particleEmitterType.minEmitBox = value;
  57458. }
  57459. },
  57460. enumerable: true,
  57461. configurable: true
  57462. });
  57463. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57464. /**
  57465. * 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.
  57466. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57467. */
  57468. get: function () {
  57469. if (this.particleEmitterType.maxEmitBox) {
  57470. return this.particleEmitterType.maxEmitBox;
  57471. }
  57472. return BABYLON.Vector3.Zero();
  57473. },
  57474. set: function (value) {
  57475. if (this.particleEmitterType.maxEmitBox) {
  57476. this.particleEmitterType.maxEmitBox = value;
  57477. }
  57478. },
  57479. enumerable: true,
  57480. configurable: true
  57481. });
  57482. /**
  57483. * Gets the maximum number of particles active at the same time.
  57484. * @returns The max number of active particles.
  57485. */
  57486. GPUParticleSystem.prototype.getCapacity = function () {
  57487. return this._capacity;
  57488. };
  57489. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57490. /**
  57491. * Gets or set the number of active particles
  57492. */
  57493. get: function () {
  57494. return this._activeCount;
  57495. },
  57496. set: function (value) {
  57497. this._activeCount = Math.min(value, this._capacity);
  57498. },
  57499. enumerable: true,
  57500. configurable: true
  57501. });
  57502. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57503. /**
  57504. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57505. */
  57506. get: function () {
  57507. return this._isAnimationSheetEnabled;
  57508. },
  57509. enumerable: true,
  57510. configurable: true
  57511. });
  57512. /**
  57513. * Is this system ready to be used/rendered
  57514. * @return true if the system is ready
  57515. */
  57516. GPUParticleSystem.prototype.isReady = function () {
  57517. if (!this._updateEffect) {
  57518. this._recreateUpdateEffect();
  57519. this._recreateRenderEffect();
  57520. return false;
  57521. }
  57522. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57523. return false;
  57524. }
  57525. return true;
  57526. };
  57527. /**
  57528. * Gets Wether the system has been started.
  57529. * @returns True if it has been started, otherwise false.
  57530. */
  57531. GPUParticleSystem.prototype.isStarted = function () {
  57532. return this._started;
  57533. };
  57534. /**
  57535. * Starts the particle system and begins to emit.
  57536. */
  57537. GPUParticleSystem.prototype.start = function () {
  57538. this._started = true;
  57539. this._stopped = false;
  57540. this._preWarmDone = false;
  57541. };
  57542. /**
  57543. * Stops the particle system.
  57544. */
  57545. GPUParticleSystem.prototype.stop = function () {
  57546. this._stopped = true;
  57547. };
  57548. /**
  57549. * Remove all active particles
  57550. */
  57551. GPUParticleSystem.prototype.reset = function () {
  57552. this._releaseBuffers();
  57553. this._releaseVAOs();
  57554. this._currentActiveCount = 0;
  57555. this._targetIndex = 0;
  57556. };
  57557. /**
  57558. * Returns the string "GPUParticleSystem"
  57559. * @returns a string containing the class name
  57560. */
  57561. GPUParticleSystem.prototype.getClassName = function () {
  57562. return "GPUParticleSystem";
  57563. };
  57564. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57565. /**
  57566. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57567. */
  57568. get: function () {
  57569. return this._isBillboardBased;
  57570. },
  57571. set: function (value) {
  57572. if (this._isBillboardBased === value) {
  57573. return;
  57574. }
  57575. this._isBillboardBased = value;
  57576. this._releaseBuffers();
  57577. },
  57578. enumerable: true,
  57579. configurable: true
  57580. });
  57581. /**
  57582. * Gets the current list of color gradients.
  57583. * You must use addColorGradient and removeColorGradient to udpate this list
  57584. * @returns the list of color gradients
  57585. */
  57586. GPUParticleSystem.prototype.getColorGradients = function () {
  57587. return this._colorGradients;
  57588. };
  57589. /**
  57590. * Gets the current list of size gradients.
  57591. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57592. * @returns the list of size gradients
  57593. */
  57594. GPUParticleSystem.prototype.getSizeGradients = function () {
  57595. return this._sizeGradients;
  57596. };
  57597. /**
  57598. * Gets the current list of angular speed gradients.
  57599. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57600. * @returns the list of angular speed gradients
  57601. */
  57602. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57603. return this._angularSpeedGradients;
  57604. };
  57605. /**
  57606. * Gets the current list of velocity gradients.
  57607. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57608. * @returns the list of angular speed gradients
  57609. */
  57610. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57611. return this._velocityGradients;
  57612. };
  57613. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57614. if (!gradients) {
  57615. return this;
  57616. }
  57617. var index = 0;
  57618. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57619. var valueGradient = gradients_1[_i];
  57620. if (valueGradient.gradient === gradient) {
  57621. gradients.splice(index, 1);
  57622. break;
  57623. }
  57624. index++;
  57625. }
  57626. if (texture) {
  57627. texture.dispose();
  57628. }
  57629. this._releaseBuffers();
  57630. return this;
  57631. };
  57632. /**
  57633. * Adds a new color gradient
  57634. * @param gradient defines the gradient to use (between 0 and 1)
  57635. * @param color defines the color to affect to the specified gradient
  57636. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57637. * @returns the current particle system
  57638. */
  57639. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57640. if (!this._colorGradients) {
  57641. this._colorGradients = [];
  57642. }
  57643. var colorGradient = new BABYLON.ColorGradient();
  57644. colorGradient.gradient = gradient;
  57645. colorGradient.color1 = color1;
  57646. this._colorGradients.push(colorGradient);
  57647. this._colorGradients.sort(function (a, b) {
  57648. if (a.gradient < b.gradient) {
  57649. return -1;
  57650. }
  57651. else if (a.gradient > b.gradient) {
  57652. return 1;
  57653. }
  57654. return 0;
  57655. });
  57656. if (this._colorGradientsTexture) {
  57657. this._colorGradientsTexture.dispose();
  57658. this._colorGradientsTexture = null;
  57659. }
  57660. this._releaseBuffers();
  57661. return this;
  57662. };
  57663. /**
  57664. * Remove a specific color gradient
  57665. * @param gradient defines the gradient to remove
  57666. * @returns the current particle system
  57667. */
  57668. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57669. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57670. this._colorGradientsTexture = null;
  57671. return this;
  57672. };
  57673. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57674. var valueGradient = new BABYLON.FactorGradient();
  57675. valueGradient.gradient = gradient;
  57676. valueGradient.factor1 = factor;
  57677. factorGradients.push(valueGradient);
  57678. factorGradients.sort(function (a, b) {
  57679. if (a.gradient < b.gradient) {
  57680. return -1;
  57681. }
  57682. else if (a.gradient > b.gradient) {
  57683. return 1;
  57684. }
  57685. return 0;
  57686. });
  57687. this._releaseBuffers();
  57688. };
  57689. /**
  57690. * Adds a new size gradient
  57691. * @param gradient defines the gradient to use (between 0 and 1)
  57692. * @param factor defines the size factor to affect to the specified gradient
  57693. * @returns the current particle system
  57694. */
  57695. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57696. if (!this._sizeGradients) {
  57697. this._sizeGradients = [];
  57698. }
  57699. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57700. if (this._sizeGradientsTexture) {
  57701. this._sizeGradientsTexture.dispose();
  57702. this._sizeGradientsTexture = null;
  57703. }
  57704. this._releaseBuffers();
  57705. return this;
  57706. };
  57707. /**
  57708. * Remove a specific size gradient
  57709. * @param gradient defines the gradient to remove
  57710. * @returns the current particle system
  57711. */
  57712. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57713. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57714. this._sizeGradientsTexture = null;
  57715. return this;
  57716. };
  57717. /**
  57718. * Adds a new angular speed gradient
  57719. * @param gradient defines the gradient to use (between 0 and 1)
  57720. * @param factor defines the size factor to affect to the specified gradient
  57721. * @returns the current particle system
  57722. */
  57723. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57724. if (!this._angularSpeedGradients) {
  57725. this._angularSpeedGradients = [];
  57726. }
  57727. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57728. if (this._angularSpeedGradientsTexture) {
  57729. this._angularSpeedGradientsTexture.dispose();
  57730. this._angularSpeedGradientsTexture = null;
  57731. }
  57732. this._releaseBuffers();
  57733. return this;
  57734. };
  57735. /**
  57736. * Remove a specific angular speed gradient
  57737. * @param gradient defines the gradient to remove
  57738. * @returns the current particle system
  57739. */
  57740. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57741. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57742. this._angularSpeedGradientsTexture = null;
  57743. return this;
  57744. };
  57745. /**
  57746. * Adds a new velocity gradient
  57747. * @param gradient defines the gradient to use (between 0 and 1)
  57748. * @param factor defines the size factor to affect to the specified gradient
  57749. * @returns the current particle system
  57750. */
  57751. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57752. if (!this._velocityGradients) {
  57753. this._velocityGradients = [];
  57754. }
  57755. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57756. if (this._velocityGradientsTexture) {
  57757. this._velocityGradientsTexture.dispose();
  57758. this._velocityGradientsTexture = null;
  57759. }
  57760. this._releaseBuffers();
  57761. return this;
  57762. };
  57763. /**
  57764. * Remove a specific velocity gradient
  57765. * @param gradient defines the gradient to remove
  57766. * @returns the current particle system
  57767. */
  57768. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57769. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57770. this._velocityGradientsTexture = null;
  57771. return this;
  57772. };
  57773. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57774. var updateVertexBuffers = {};
  57775. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57776. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57777. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57778. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57779. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57780. var offset = 12;
  57781. if (!this._colorGradientsTexture) {
  57782. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57783. offset += 4;
  57784. }
  57785. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57786. offset += 3;
  57787. if (!this._isBillboardBased) {
  57788. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57789. offset += 3;
  57790. }
  57791. if (this._angularSpeedGradientsTexture) {
  57792. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57793. offset += 1;
  57794. }
  57795. else {
  57796. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57797. offset += 2;
  57798. }
  57799. if (this._isAnimationSheetEnabled) {
  57800. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57801. offset += 1;
  57802. }
  57803. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57804. this._engine.bindArrayBuffer(null);
  57805. return vao;
  57806. };
  57807. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57808. var renderVertexBuffers = {};
  57809. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57810. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57811. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57812. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57813. var offset = 12;
  57814. if (!this._colorGradientsTexture) {
  57815. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57816. offset += 4;
  57817. }
  57818. offset += 3; // Direction
  57819. if (!this._isBillboardBased) {
  57820. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57821. offset += 3;
  57822. }
  57823. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57824. if (this._angularSpeedGradientsTexture) {
  57825. offset++;
  57826. }
  57827. else {
  57828. offset += 2;
  57829. }
  57830. if (this._isAnimationSheetEnabled) {
  57831. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57832. offset += 1;
  57833. }
  57834. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57835. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57836. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57837. this._engine.bindArrayBuffer(null);
  57838. return vao;
  57839. };
  57840. GPUParticleSystem.prototype._initialize = function (force) {
  57841. if (force === void 0) { force = false; }
  57842. if (this._buffer0 && !force) {
  57843. return;
  57844. }
  57845. var engine = this._scene.getEngine();
  57846. var data = new Array();
  57847. if (!this.isBillboardBased) {
  57848. this._attributesStrideSize += 3;
  57849. }
  57850. if (this._colorGradientsTexture) {
  57851. this._attributesStrideSize -= 4;
  57852. }
  57853. if (this._angularSpeedGradientsTexture) {
  57854. this._attributesStrideSize -= 1;
  57855. }
  57856. if (this._isAnimationSheetEnabled) {
  57857. this._attributesStrideSize += 1;
  57858. }
  57859. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57860. // position
  57861. data.push(0.0);
  57862. data.push(0.0);
  57863. data.push(0.0);
  57864. // Age and life
  57865. data.push(0.0); // create the particle as a dead one to create a new one at start
  57866. data.push(0.0);
  57867. // Seed
  57868. data.push(Math.random());
  57869. data.push(Math.random());
  57870. data.push(Math.random());
  57871. data.push(Math.random());
  57872. // Size
  57873. data.push(0.0);
  57874. data.push(0.0);
  57875. data.push(0.0);
  57876. if (!this._colorGradientsTexture) {
  57877. // color
  57878. data.push(0.0);
  57879. data.push(0.0);
  57880. data.push(0.0);
  57881. data.push(0.0);
  57882. }
  57883. // direction
  57884. data.push(0.0);
  57885. data.push(0.0);
  57886. data.push(0.0);
  57887. if (!this.isBillboardBased) {
  57888. // initialDirection
  57889. data.push(0.0);
  57890. data.push(0.0);
  57891. data.push(0.0);
  57892. }
  57893. // angle
  57894. data.push(0.0);
  57895. if (!this._angularSpeedGradientsTexture) {
  57896. data.push(0.0);
  57897. }
  57898. if (this._isAnimationSheetEnabled) {
  57899. data.push(0.0);
  57900. }
  57901. }
  57902. // Sprite data
  57903. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57904. -0.5, 0.5, 0, 1,
  57905. -0.5, -0.5, 0, 0,
  57906. 0.5, -0.5, 1, 0]);
  57907. // Buffers
  57908. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57909. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57910. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57911. // Update VAO
  57912. this._updateVAO = [];
  57913. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57914. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57915. // Render VAO
  57916. this._renderVAO = [];
  57917. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57918. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57919. // Links
  57920. this._sourceBuffer = this._buffer0;
  57921. this._targetBuffer = this._buffer1;
  57922. };
  57923. /** @hidden */
  57924. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57925. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57926. if (this._isBillboardBased) {
  57927. defines += "\n#define BILLBOARD";
  57928. }
  57929. if (this._colorGradientsTexture) {
  57930. defines += "\n#define COLORGRADIENTS";
  57931. }
  57932. if (this._sizeGradientsTexture) {
  57933. defines += "\n#define SIZEGRADIENTS";
  57934. }
  57935. if (this._angularSpeedGradientsTexture) {
  57936. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57937. }
  57938. if (this._velocityGradientsTexture) {
  57939. defines += "\n#define VELOCITYGRADIENTS";
  57940. }
  57941. if (this.isAnimationSheetEnabled) {
  57942. defines += "\n#define ANIMATESHEET";
  57943. }
  57944. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57945. return;
  57946. }
  57947. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57948. if (!this._colorGradientsTexture) {
  57949. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57950. }
  57951. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57952. if (!this._isBillboardBased) {
  57953. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57954. }
  57955. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57956. if (this.isAnimationSheetEnabled) {
  57957. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57958. }
  57959. this._updateEffectOptions.defines = defines;
  57960. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57961. };
  57962. /** @hidden */
  57963. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57964. var defines = "";
  57965. if (this._scene.clipPlane) {
  57966. defines = "\n#define CLIPPLANE";
  57967. }
  57968. if (this._isBillboardBased) {
  57969. defines += "\n#define BILLBOARD";
  57970. switch (this.billboardMode) {
  57971. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57972. defines += "\n#define BILLBOARDY";
  57973. break;
  57974. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57975. default:
  57976. break;
  57977. }
  57978. }
  57979. if (this._colorGradientsTexture) {
  57980. defines += "\n#define COLORGRADIENTS";
  57981. }
  57982. if (this.isAnimationSheetEnabled) {
  57983. defines += "\n#define ANIMATESHEET";
  57984. }
  57985. if (this._renderEffect && this._renderEffect.defines === defines) {
  57986. return;
  57987. }
  57988. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57989. };
  57990. /**
  57991. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57992. * @param preWarm defines if we are in the pre-warmimg phase
  57993. */
  57994. GPUParticleSystem.prototype.animate = function (preWarm) {
  57995. if (preWarm === void 0) { preWarm = false; }
  57996. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57997. this._actualFrame += this._timeDelta;
  57998. if (!this._stopped) {
  57999. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58000. this.stop();
  58001. }
  58002. }
  58003. };
  58004. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  58005. var texture = this[textureName];
  58006. if (!factorGradients || !factorGradients.length || texture) {
  58007. return;
  58008. }
  58009. var data = new Float32Array(this._rawTextureWidth);
  58010. for (var x = 0; x < this._rawTextureWidth; x++) {
  58011. var ratio = x / this._rawTextureWidth;
  58012. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  58013. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58014. });
  58015. }
  58016. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58017. };
  58018. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  58019. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  58020. };
  58021. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  58022. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  58023. };
  58024. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  58025. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  58026. };
  58027. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  58028. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  58029. return;
  58030. }
  58031. var data = new Uint8Array(this._rawTextureWidth * 4);
  58032. var tmpColor = BABYLON.Tmp.Color4[0];
  58033. for (var x = 0; x < this._rawTextureWidth; x++) {
  58034. var ratio = x / this._rawTextureWidth;
  58035. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  58036. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  58037. data[x * 4] = tmpColor.r * 255;
  58038. data[x * 4 + 1] = tmpColor.g * 255;
  58039. data[x * 4 + 2] = tmpColor.b * 255;
  58040. data[x * 4 + 3] = tmpColor.a * 255;
  58041. });
  58042. }
  58043. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58044. };
  58045. /**
  58046. * Renders the particle system in its current state
  58047. * @param preWarm defines if the system should only update the particles but not render them
  58048. * @returns the current number of particles
  58049. */
  58050. GPUParticleSystem.prototype.render = function (preWarm) {
  58051. if (preWarm === void 0) { preWarm = false; }
  58052. if (!this._started) {
  58053. return 0;
  58054. }
  58055. this._createColorGradientTexture();
  58056. this._createSizeGradientTexture();
  58057. this._createAngularSpeedGradientTexture();
  58058. this._createVelocityGradientTexture();
  58059. this._recreateUpdateEffect();
  58060. this._recreateRenderEffect();
  58061. if (!this.isReady()) {
  58062. return 0;
  58063. }
  58064. if (!preWarm) {
  58065. if (!this._preWarmDone && this.preWarmCycles) {
  58066. for (var index = 0; index < this.preWarmCycles; index++) {
  58067. this.animate(true);
  58068. this.render(true);
  58069. }
  58070. this._preWarmDone = true;
  58071. }
  58072. if (this._currentRenderId === this._scene.getRenderId()) {
  58073. return 0;
  58074. }
  58075. this._currentRenderId = this._scene.getRenderId();
  58076. }
  58077. // Get everything ready to render
  58078. this._initialize();
  58079. this._accumulatedCount += this.emitRate * this._timeDelta;
  58080. if (this._accumulatedCount > 1) {
  58081. var intPart = this._accumulatedCount | 0;
  58082. this._accumulatedCount -= intPart;
  58083. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  58084. }
  58085. if (!this._currentActiveCount) {
  58086. return 0;
  58087. }
  58088. // Enable update effect
  58089. this._engine.enableEffect(this._updateEffect);
  58090. this._engine.setState(false);
  58091. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58092. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58093. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58094. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58095. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  58096. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58097. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58098. if (!this._colorGradientsTexture) {
  58099. this._updateEffect.setDirectColor4("color1", this.color1);
  58100. this._updateEffect.setDirectColor4("color2", this.color2);
  58101. }
  58102. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58103. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58104. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  58105. this._updateEffect.setVector3("gravity", this.gravity);
  58106. if (this._sizeGradientsTexture) {
  58107. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  58108. }
  58109. if (this._angularSpeedGradientsTexture) {
  58110. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  58111. }
  58112. if (this._velocityGradientsTexture) {
  58113. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  58114. }
  58115. if (this.particleEmitterType) {
  58116. this.particleEmitterType.applyToShader(this._updateEffect);
  58117. }
  58118. if (this._isAnimationSheetEnabled) {
  58119. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  58120. }
  58121. var emitterWM;
  58122. if (this.emitter.position) {
  58123. var emitterMesh = this.emitter;
  58124. emitterWM = emitterMesh.getWorldMatrix();
  58125. }
  58126. else {
  58127. var emitterPosition = this.emitter;
  58128. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58129. }
  58130. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58131. // Bind source VAO
  58132. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58133. // Update
  58134. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58135. this._engine.setRasterizerState(false);
  58136. this._engine.beginTransformFeedback();
  58137. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58138. this._engine.endTransformFeedback();
  58139. this._engine.setRasterizerState(true);
  58140. this._engine.bindTransformFeedbackBuffer(null);
  58141. if (!preWarm) {
  58142. // Enable render effect
  58143. this._engine.enableEffect(this._renderEffect);
  58144. var viewMatrix = this._scene.getViewMatrix();
  58145. this._renderEffect.setMatrix("view", viewMatrix);
  58146. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58147. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58148. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  58149. if (this._colorGradientsTexture) {
  58150. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  58151. }
  58152. else {
  58153. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58154. }
  58155. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58156. var baseSize = this.particleTexture.getBaseSize();
  58157. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58158. }
  58159. if (this._isBillboardBased) {
  58160. var camera = this._scene.activeCamera;
  58161. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  58162. }
  58163. if (this._scene.clipPlane) {
  58164. var clipPlane = this._scene.clipPlane;
  58165. var invView = viewMatrix.clone();
  58166. invView.invert();
  58167. this._renderEffect.setMatrix("invView", invView);
  58168. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58169. }
  58170. // Draw order
  58171. switch (this.blendMode) {
  58172. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  58173. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58174. break;
  58175. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  58176. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58177. break;
  58178. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  58179. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58180. break;
  58181. }
  58182. if (this.forceDepthWrite) {
  58183. this._engine.setDepthWrite(true);
  58184. }
  58185. // Bind source VAO
  58186. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58187. // Render
  58188. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58189. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58190. }
  58191. // Switch VAOs
  58192. this._targetIndex++;
  58193. if (this._targetIndex === 2) {
  58194. this._targetIndex = 0;
  58195. }
  58196. // Switch buffers
  58197. var tmpBuffer = this._sourceBuffer;
  58198. this._sourceBuffer = this._targetBuffer;
  58199. this._targetBuffer = tmpBuffer;
  58200. return this._currentActiveCount;
  58201. };
  58202. /**
  58203. * Rebuilds the particle system
  58204. */
  58205. GPUParticleSystem.prototype.rebuild = function () {
  58206. this._initialize(true);
  58207. };
  58208. GPUParticleSystem.prototype._releaseBuffers = function () {
  58209. if (this._buffer0) {
  58210. this._buffer0.dispose();
  58211. this._buffer0 = null;
  58212. }
  58213. if (this._buffer1) {
  58214. this._buffer1.dispose();
  58215. this._buffer1 = null;
  58216. }
  58217. if (this._spriteBuffer) {
  58218. this._spriteBuffer.dispose();
  58219. this._spriteBuffer = null;
  58220. }
  58221. };
  58222. GPUParticleSystem.prototype._releaseVAOs = function () {
  58223. if (!this._updateVAO) {
  58224. return;
  58225. }
  58226. for (var index = 0; index < this._updateVAO.length; index++) {
  58227. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58228. }
  58229. this._updateVAO = [];
  58230. for (var index = 0; index < this._renderVAO.length; index++) {
  58231. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58232. }
  58233. this._renderVAO = [];
  58234. };
  58235. /**
  58236. * Disposes the particle system and free the associated resources
  58237. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58238. */
  58239. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58240. if (disposeTexture === void 0) { disposeTexture = true; }
  58241. var index = this._scene.particleSystems.indexOf(this);
  58242. if (index > -1) {
  58243. this._scene.particleSystems.splice(index, 1);
  58244. }
  58245. this._releaseBuffers();
  58246. this._releaseVAOs();
  58247. if (this._colorGradientsTexture) {
  58248. this._colorGradientsTexture.dispose();
  58249. this._colorGradientsTexture = null;
  58250. }
  58251. if (this._sizeGradientsTexture) {
  58252. this._sizeGradientsTexture.dispose();
  58253. this._sizeGradientsTexture = null;
  58254. }
  58255. if (this._angularSpeedGradientsTexture) {
  58256. this._angularSpeedGradientsTexture.dispose();
  58257. this._angularSpeedGradientsTexture = null;
  58258. }
  58259. if (this._velocityGradientsTexture) {
  58260. this._velocityGradientsTexture.dispose();
  58261. this._velocityGradientsTexture = null;
  58262. }
  58263. if (this._randomTexture) {
  58264. this._randomTexture.dispose();
  58265. this._randomTexture = null;
  58266. }
  58267. if (this._randomTexture2) {
  58268. this._randomTexture2.dispose();
  58269. this._randomTexture2 = null;
  58270. }
  58271. if (disposeTexture && this.particleTexture) {
  58272. this.particleTexture.dispose();
  58273. this.particleTexture = null;
  58274. }
  58275. // Callback
  58276. this.onDisposeObservable.notifyObservers(this);
  58277. this.onDisposeObservable.clear();
  58278. };
  58279. /**
  58280. * Clones the particle system.
  58281. * @param name The name of the cloned object
  58282. * @param newEmitter The new emitter to use
  58283. * @returns the cloned particle system
  58284. */
  58285. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58286. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58287. BABYLON.Tools.DeepCopy(this, result);
  58288. if (newEmitter === undefined) {
  58289. newEmitter = this.emitter;
  58290. }
  58291. result.emitter = newEmitter;
  58292. if (this.particleTexture) {
  58293. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58294. }
  58295. return result;
  58296. };
  58297. /**
  58298. * Serializes the particle system to a JSON object.
  58299. * @returns the JSON object
  58300. */
  58301. GPUParticleSystem.prototype.serialize = function () {
  58302. var serializationObject = {};
  58303. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58304. serializationObject.activeParticleCount = this.activeParticleCount;
  58305. return serializationObject;
  58306. };
  58307. /**
  58308. * Parses a JSON object to create a GPU particle system.
  58309. * @param parsedParticleSystem The JSON object to parse
  58310. * @param scene The scene to create the particle system in
  58311. * @param rootUrl The root url to use to load external dependencies like texture
  58312. * @returns the parsed GPU particle system
  58313. */
  58314. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58315. var name = parsedParticleSystem.name;
  58316. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58317. if (parsedParticleSystem.activeParticleCount) {
  58318. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58319. }
  58320. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58321. return particleSystem;
  58322. };
  58323. return GPUParticleSystem;
  58324. }());
  58325. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58326. })(BABYLON || (BABYLON = {}));
  58327. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58328. var BABYLON;
  58329. (function (BABYLON) {
  58330. /**
  58331. * Represents one particle of a solid particle system.
  58332. */
  58333. var SolidParticle = /** @class */ (function () {
  58334. /**
  58335. * Creates a Solid Particle object.
  58336. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58337. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58338. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58339. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58340. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58341. * @param shapeId (integer) is the model shape identifier in the SPS.
  58342. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58343. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58344. */
  58345. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58346. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58347. /**
  58348. * particle global index
  58349. */
  58350. this.idx = 0;
  58351. /**
  58352. * The color of the particle
  58353. */
  58354. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58355. /**
  58356. * The world space position of the particle.
  58357. */
  58358. this.position = BABYLON.Vector3.Zero();
  58359. /**
  58360. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58361. */
  58362. this.rotation = BABYLON.Vector3.Zero();
  58363. /**
  58364. * The scaling of the particle.
  58365. */
  58366. this.scaling = BABYLON.Vector3.One();
  58367. /**
  58368. * The uvs of the particle.
  58369. */
  58370. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58371. /**
  58372. * The current speed of the particle.
  58373. */
  58374. this.velocity = BABYLON.Vector3.Zero();
  58375. /**
  58376. * The pivot point in the particle local space.
  58377. */
  58378. this.pivot = BABYLON.Vector3.Zero();
  58379. /**
  58380. * Must the particle be translated from its pivot point in its local space ?
  58381. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58382. * Default : false
  58383. */
  58384. this.translateFromPivot = false;
  58385. /**
  58386. * Is the particle active or not ?
  58387. */
  58388. this.alive = true;
  58389. /**
  58390. * Is the particle visible or not ?
  58391. */
  58392. this.isVisible = true;
  58393. /**
  58394. * Index of this particle in the global "positions" array (Internal use)
  58395. */
  58396. this._pos = 0;
  58397. /**
  58398. * Index of this particle in the global "indices" array (Internal use)
  58399. */
  58400. this._ind = 0;
  58401. /**
  58402. * ModelShape id of this particle
  58403. */
  58404. this.shapeId = 0;
  58405. /**
  58406. * Index of the particle in its shape id (Internal use)
  58407. */
  58408. this.idxInShape = 0;
  58409. /**
  58410. * Still set as invisible in order to skip useless computations (Internal use)
  58411. */
  58412. this._stillInvisible = false;
  58413. /**
  58414. * Last computed particle rotation matrix
  58415. */
  58416. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58417. /**
  58418. * Parent particle Id, if any.
  58419. * Default null.
  58420. */
  58421. this.parentId = null;
  58422. /**
  58423. * Internal global position in the SPS.
  58424. */
  58425. this._globalPosition = BABYLON.Vector3.Zero();
  58426. this.idx = particleIndex;
  58427. this._pos = positionIndex;
  58428. this._ind = indiceIndex;
  58429. this._model = model;
  58430. this.shapeId = shapeId;
  58431. this.idxInShape = idxInShape;
  58432. this._sps = sps;
  58433. if (modelBoundingInfo) {
  58434. this._modelBoundingInfo = modelBoundingInfo;
  58435. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58436. }
  58437. }
  58438. Object.defineProperty(SolidParticle.prototype, "scale", {
  58439. /**
  58440. * Legacy support, changed scale to scaling
  58441. */
  58442. get: function () {
  58443. return this.scaling;
  58444. },
  58445. /**
  58446. * Legacy support, changed scale to scaling
  58447. */
  58448. set: function (scale) {
  58449. this.scaling = scale;
  58450. },
  58451. enumerable: true,
  58452. configurable: true
  58453. });
  58454. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58455. /**
  58456. * Legacy support, changed quaternion to rotationQuaternion
  58457. */
  58458. get: function () {
  58459. return this.rotationQuaternion;
  58460. },
  58461. /**
  58462. * Legacy support, changed quaternion to rotationQuaternion
  58463. */
  58464. set: function (q) {
  58465. this.rotationQuaternion = q;
  58466. },
  58467. enumerable: true,
  58468. configurable: true
  58469. });
  58470. /**
  58471. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58472. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58473. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58474. * @returns true if it intersects
  58475. */
  58476. SolidParticle.prototype.intersectsMesh = function (target) {
  58477. if (!this._boundingInfo || !target._boundingInfo) {
  58478. return false;
  58479. }
  58480. if (this._sps._bSphereOnly) {
  58481. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58482. }
  58483. return this._boundingInfo.intersects(target._boundingInfo, false);
  58484. };
  58485. return SolidParticle;
  58486. }());
  58487. BABYLON.SolidParticle = SolidParticle;
  58488. /**
  58489. * Represents the shape of the model used by one particle of a solid particle system.
  58490. * SPS internal tool, don't use it manually.
  58491. */
  58492. var ModelShape = /** @class */ (function () {
  58493. /**
  58494. * 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.
  58495. * SPS internal tool, don't use it manually.
  58496. * @hidden
  58497. */
  58498. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58499. /**
  58500. * length of the shape in the model indices array (internal use)
  58501. */
  58502. this._indicesLength = 0;
  58503. this.shapeID = id;
  58504. this._shape = shape;
  58505. this._indicesLength = indicesLength;
  58506. this._shapeUV = shapeUV;
  58507. this._positionFunction = posFunction;
  58508. this._vertexFunction = vtxFunction;
  58509. }
  58510. return ModelShape;
  58511. }());
  58512. BABYLON.ModelShape = ModelShape;
  58513. /**
  58514. * Represents a Depth Sorted Particle in the solid particle system.
  58515. */
  58516. var DepthSortedParticle = /** @class */ (function () {
  58517. function DepthSortedParticle() {
  58518. /**
  58519. * Index of the particle in the "indices" array
  58520. */
  58521. this.ind = 0;
  58522. /**
  58523. * Length of the particle shape in the "indices" array
  58524. */
  58525. this.indicesLength = 0;
  58526. /**
  58527. * Squared distance from the particle to the camera
  58528. */
  58529. this.sqDistance = 0.0;
  58530. }
  58531. return DepthSortedParticle;
  58532. }());
  58533. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58534. })(BABYLON || (BABYLON = {}));
  58535. //# sourceMappingURL=babylon.solidParticle.js.map
  58536. var BABYLON;
  58537. (function (BABYLON) {
  58538. /**
  58539. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58540. *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.
  58541. * The SPS is also a particle system. It provides some methods to manage the particles.
  58542. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58543. *
  58544. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58545. */
  58546. var SolidParticleSystem = /** @class */ (function () {
  58547. /**
  58548. * Creates a SPS (Solid Particle System) object.
  58549. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58550. * @param scene (Scene) is the scene in which the SPS is added.
  58551. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58552. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58553. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58554. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58555. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58556. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58557. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58558. */
  58559. function SolidParticleSystem(name, scene, options) {
  58560. /**
  58561. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58562. * Example : var p = SPS.particles[i];
  58563. */
  58564. this.particles = new Array();
  58565. /**
  58566. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58567. */
  58568. this.nbParticles = 0;
  58569. /**
  58570. * If the particles must ever face the camera (default false). Useful for planar particles.
  58571. */
  58572. this.billboard = false;
  58573. /**
  58574. * Recompute normals when adding a shape
  58575. */
  58576. this.recomputeNormals = true;
  58577. /**
  58578. * This a counter ofr your own usage. It's not set by any SPS functions.
  58579. */
  58580. this.counter = 0;
  58581. /**
  58582. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58583. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58584. */
  58585. this.vars = {};
  58586. /**
  58587. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58588. */
  58589. this._bSphereOnly = false;
  58590. /**
  58591. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58592. */
  58593. this._bSphereRadiusFactor = 1.0;
  58594. this._positions = new Array();
  58595. this._indices = new Array();
  58596. this._normals = new Array();
  58597. this._colors = new Array();
  58598. this._uvs = new Array();
  58599. this._index = 0; // indices index
  58600. this._updatable = true;
  58601. this._pickable = false;
  58602. this._isVisibilityBoxLocked = false;
  58603. this._alwaysVisible = false;
  58604. this._depthSort = false;
  58605. this._shapeCounter = 0;
  58606. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58607. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58608. this._computeParticleColor = true;
  58609. this._computeParticleTexture = true;
  58610. this._computeParticleRotation = true;
  58611. this._computeParticleVertex = false;
  58612. this._computeBoundingBox = false;
  58613. this._depthSortParticles = true;
  58614. this._cam_axisZ = BABYLON.Vector3.Zero();
  58615. this._cam_axisY = BABYLON.Vector3.Zero();
  58616. this._cam_axisX = BABYLON.Vector3.Zero();
  58617. this._axisZ = BABYLON.Axis.Z;
  58618. this._camDir = BABYLON.Vector3.Zero();
  58619. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58620. this._rotMatrix = new BABYLON.Matrix();
  58621. this._invertMatrix = new BABYLON.Matrix();
  58622. this._rotated = BABYLON.Vector3.Zero();
  58623. this._quaternion = new BABYLON.Quaternion();
  58624. this._vertex = BABYLON.Vector3.Zero();
  58625. this._normal = BABYLON.Vector3.Zero();
  58626. this._yaw = 0.0;
  58627. this._pitch = 0.0;
  58628. this._roll = 0.0;
  58629. this._halfroll = 0.0;
  58630. this._halfpitch = 0.0;
  58631. this._halfyaw = 0.0;
  58632. this._sinRoll = 0.0;
  58633. this._cosRoll = 0.0;
  58634. this._sinPitch = 0.0;
  58635. this._cosPitch = 0.0;
  58636. this._sinYaw = 0.0;
  58637. this._cosYaw = 0.0;
  58638. this._mustUnrotateFixedNormals = false;
  58639. this._minimum = BABYLON.Vector3.Zero();
  58640. this._maximum = BABYLON.Vector3.Zero();
  58641. this._minBbox = BABYLON.Vector3.Zero();
  58642. this._maxBbox = BABYLON.Vector3.Zero();
  58643. this._particlesIntersect = false;
  58644. this._depthSortFunction = function (p1, p2) {
  58645. return (p2.sqDistance - p1.sqDistance);
  58646. };
  58647. this._needs32Bits = false;
  58648. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58649. this._scaledPivot = BABYLON.Vector3.Zero();
  58650. this._particleHasParent = false;
  58651. this.name = name;
  58652. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58653. this._camera = scene.activeCamera;
  58654. this._pickable = options ? options.isPickable : false;
  58655. this._depthSort = options ? options.enableDepthSort : false;
  58656. this._particlesIntersect = options ? options.particleIntersection : false;
  58657. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58658. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58659. if (options && options.updatable !== undefined) {
  58660. this._updatable = options.updatable;
  58661. }
  58662. else {
  58663. this._updatable = true;
  58664. }
  58665. if (this._pickable) {
  58666. this.pickedParticles = [];
  58667. }
  58668. if (this._depthSort) {
  58669. this.depthSortedParticles = [];
  58670. }
  58671. }
  58672. /**
  58673. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58674. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58675. * @returns the created mesh
  58676. */
  58677. SolidParticleSystem.prototype.buildMesh = function () {
  58678. if (this.nbParticles === 0) {
  58679. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58680. this.addShape(triangle, 1);
  58681. triangle.dispose();
  58682. }
  58683. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58684. this._positions32 = new Float32Array(this._positions);
  58685. this._uvs32 = new Float32Array(this._uvs);
  58686. this._colors32 = new Float32Array(this._colors);
  58687. if (this.recomputeNormals) {
  58688. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58689. }
  58690. this._normals32 = new Float32Array(this._normals);
  58691. this._fixedNormal32 = new Float32Array(this._normals);
  58692. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58693. this._unrotateFixedNormals();
  58694. }
  58695. var vertexData = new BABYLON.VertexData();
  58696. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58697. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58698. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58699. if (this._uvs32.length > 0) {
  58700. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58701. }
  58702. if (this._colors32.length > 0) {
  58703. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58704. }
  58705. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58706. vertexData.applyToMesh(mesh, this._updatable);
  58707. this.mesh = mesh;
  58708. this.mesh.isPickable = this._pickable;
  58709. // free memory
  58710. if (!this._depthSort) {
  58711. this._indices = null;
  58712. }
  58713. this._positions = null;
  58714. this._normals = null;
  58715. this._uvs = null;
  58716. this._colors = null;
  58717. if (!this._updatable) {
  58718. this.particles.length = 0;
  58719. }
  58720. return mesh;
  58721. };
  58722. /**
  58723. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58724. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58725. * Thus the particles generated from `digest()` have their property `position` set yet.
  58726. * @param mesh ( Mesh ) is the mesh to be digested
  58727. * @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
  58728. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58729. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58730. * @returns the current SPS
  58731. */
  58732. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58733. var size = (options && options.facetNb) || 1;
  58734. var number = (options && options.number) || 0;
  58735. var delta = (options && options.delta) || 0;
  58736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58737. var meshInd = mesh.getIndices();
  58738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58741. var f = 0; // facet counter
  58742. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58743. // compute size from number
  58744. if (number) {
  58745. number = (number > totalFacets) ? totalFacets : number;
  58746. size = Math.round(totalFacets / number);
  58747. delta = 0;
  58748. }
  58749. else {
  58750. size = (size > totalFacets) ? totalFacets : size;
  58751. }
  58752. var facetPos = []; // submesh positions
  58753. var facetInd = []; // submesh indices
  58754. var facetUV = []; // submesh UV
  58755. var facetCol = []; // submesh colors
  58756. var barycenter = BABYLON.Vector3.Zero();
  58757. var sizeO = size;
  58758. while (f < totalFacets) {
  58759. size = sizeO + Math.floor((1 + delta) * Math.random());
  58760. if (f > totalFacets - size) {
  58761. size = totalFacets - f;
  58762. }
  58763. // reset temp arrays
  58764. facetPos.length = 0;
  58765. facetInd.length = 0;
  58766. facetUV.length = 0;
  58767. facetCol.length = 0;
  58768. // iterate over "size" facets
  58769. var fi = 0;
  58770. for (var j = f * 3; j < (f + size) * 3; j++) {
  58771. facetInd.push(fi);
  58772. var i = meshInd[j];
  58773. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58774. if (meshUV) {
  58775. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58776. }
  58777. if (meshCol) {
  58778. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58779. }
  58780. fi++;
  58781. }
  58782. // create a model shape for each single particle
  58783. var idx = this.nbParticles;
  58784. var shape = this._posToShape(facetPos);
  58785. var shapeUV = this._uvsToShapeUV(facetUV);
  58786. // compute the barycenter of the shape
  58787. var v;
  58788. for (v = 0; v < shape.length; v++) {
  58789. barycenter.addInPlace(shape[v]);
  58790. }
  58791. barycenter.scaleInPlace(1 / shape.length);
  58792. // shift the shape from its barycenter to the origin
  58793. for (v = 0; v < shape.length; v++) {
  58794. shape[v].subtractInPlace(barycenter);
  58795. }
  58796. var bInfo;
  58797. if (this._particlesIntersect) {
  58798. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58799. }
  58800. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58801. // add the particle in the SPS
  58802. var currentPos = this._positions.length;
  58803. var currentInd = this._indices.length;
  58804. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58805. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58806. // initialize the particle position
  58807. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58808. this._index += shape.length;
  58809. idx++;
  58810. this.nbParticles++;
  58811. this._shapeCounter++;
  58812. f += size;
  58813. }
  58814. return this;
  58815. };
  58816. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58817. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58818. var index = 0;
  58819. var idx = 0;
  58820. for (var p = 0; p < this.particles.length; p++) {
  58821. this._particle = this.particles[p];
  58822. this._shape = this._particle._model._shape;
  58823. if (this._particle.rotationQuaternion) {
  58824. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58825. }
  58826. else {
  58827. this._yaw = this._particle.rotation.y;
  58828. this._pitch = this._particle.rotation.x;
  58829. this._roll = this._particle.rotation.z;
  58830. this._quaternionRotationYPR();
  58831. }
  58832. this._quaternionToRotationMatrix();
  58833. this._rotMatrix.invertToRef(this._invertMatrix);
  58834. for (var pt = 0; pt < this._shape.length; pt++) {
  58835. idx = index + pt * 3;
  58836. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58837. this._fixedNormal32[idx] = this._normal.x;
  58838. this._fixedNormal32[idx + 1] = this._normal.y;
  58839. this._fixedNormal32[idx + 2] = this._normal.z;
  58840. }
  58841. index = idx + 3;
  58842. }
  58843. };
  58844. //reset copy
  58845. SolidParticleSystem.prototype._resetCopy = function () {
  58846. this._copy.position.x = 0;
  58847. this._copy.position.y = 0;
  58848. this._copy.position.z = 0;
  58849. this._copy.rotation.x = 0;
  58850. this._copy.rotation.y = 0;
  58851. this._copy.rotation.z = 0;
  58852. this._copy.rotationQuaternion = null;
  58853. this._copy.scaling.x = 1.0;
  58854. this._copy.scaling.y = 1.0;
  58855. this._copy.scaling.z = 1.0;
  58856. this._copy.uvs.x = 0;
  58857. this._copy.uvs.y = 0;
  58858. this._copy.uvs.z = 1.0;
  58859. this._copy.uvs.w = 1.0;
  58860. this._copy.color = null;
  58861. this._copy.translateFromPivot = false;
  58862. };
  58863. // _meshBuilder : inserts the shape model in the global SPS mesh
  58864. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58865. var i;
  58866. var u = 0;
  58867. var c = 0;
  58868. var n = 0;
  58869. this._resetCopy();
  58870. if (options && options.positionFunction) { // call to custom positionFunction
  58871. options.positionFunction(this._copy, idx, idxInShape);
  58872. this._mustUnrotateFixedNormals = true;
  58873. }
  58874. if (this._copy.rotationQuaternion) {
  58875. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58876. }
  58877. else {
  58878. this._yaw = this._copy.rotation.y;
  58879. this._pitch = this._copy.rotation.x;
  58880. this._roll = this._copy.rotation.z;
  58881. this._quaternionRotationYPR();
  58882. }
  58883. this._quaternionToRotationMatrix();
  58884. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58885. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58886. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58887. if (this._copy.translateFromPivot) {
  58888. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58889. }
  58890. else {
  58891. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58892. }
  58893. for (i = 0; i < shape.length; i++) {
  58894. this._vertex.x = shape[i].x;
  58895. this._vertex.y = shape[i].y;
  58896. this._vertex.z = shape[i].z;
  58897. if (options && options.vertexFunction) {
  58898. options.vertexFunction(this._copy, this._vertex, i);
  58899. }
  58900. this._vertex.x *= this._copy.scaling.x;
  58901. this._vertex.y *= this._copy.scaling.y;
  58902. this._vertex.z *= this._copy.scaling.z;
  58903. this._vertex.x -= this._scaledPivot.x;
  58904. this._vertex.y -= this._scaledPivot.y;
  58905. this._vertex.z -= this._scaledPivot.z;
  58906. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58907. this._rotated.addInPlace(this._pivotBackTranslation);
  58908. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58909. if (meshUV) {
  58910. 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);
  58911. u += 2;
  58912. }
  58913. if (this._copy.color) {
  58914. this._color = this._copy.color;
  58915. }
  58916. else if (meshCol && meshCol[c] !== undefined) {
  58917. this._color.r = meshCol[c];
  58918. this._color.g = meshCol[c + 1];
  58919. this._color.b = meshCol[c + 2];
  58920. this._color.a = meshCol[c + 3];
  58921. }
  58922. else {
  58923. this._color.r = 1.0;
  58924. this._color.g = 1.0;
  58925. this._color.b = 1.0;
  58926. this._color.a = 1.0;
  58927. }
  58928. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58929. c += 4;
  58930. if (!this.recomputeNormals && meshNor) {
  58931. this._normal.x = meshNor[n];
  58932. this._normal.y = meshNor[n + 1];
  58933. this._normal.z = meshNor[n + 2];
  58934. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58935. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58936. n += 3;
  58937. }
  58938. }
  58939. for (i = 0; i < meshInd.length; i++) {
  58940. var current_ind = p + meshInd[i];
  58941. indices.push(current_ind);
  58942. if (current_ind > 65535) {
  58943. this._needs32Bits = true;
  58944. }
  58945. }
  58946. if (this._pickable) {
  58947. var nbfaces = meshInd.length / 3;
  58948. for (i = 0; i < nbfaces; i++) {
  58949. this.pickedParticles.push({ idx: idx, faceId: i });
  58950. }
  58951. }
  58952. if (this._depthSort) {
  58953. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58954. }
  58955. return this._copy;
  58956. };
  58957. // returns a shape array from positions array
  58958. SolidParticleSystem.prototype._posToShape = function (positions) {
  58959. var shape = [];
  58960. for (var i = 0; i < positions.length; i += 3) {
  58961. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58962. }
  58963. return shape;
  58964. };
  58965. // returns a shapeUV array from a Vector4 uvs
  58966. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58967. var shapeUV = [];
  58968. if (uvs) {
  58969. for (var i = 0; i < uvs.length; i++)
  58970. shapeUV.push(uvs[i]);
  58971. }
  58972. return shapeUV;
  58973. };
  58974. // adds a new particle object in the particles array
  58975. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58976. if (bInfo === void 0) { bInfo = null; }
  58977. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58978. this.particles.push(sp);
  58979. return sp;
  58980. };
  58981. /**
  58982. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58983. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58984. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58985. * @param nb (positive integer) the number of particles to be created from this model
  58986. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58987. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58988. * @returns the number of shapes in the system
  58989. */
  58990. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58991. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58992. var meshInd = mesh.getIndices();
  58993. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58994. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58995. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58996. var bbInfo;
  58997. if (this._particlesIntersect) {
  58998. bbInfo = mesh.getBoundingInfo();
  58999. }
  59000. var shape = this._posToShape(meshPos);
  59001. var shapeUV = this._uvsToShapeUV(meshUV);
  59002. var posfunc = options ? options.positionFunction : null;
  59003. var vtxfunc = options ? options.vertexFunction : null;
  59004. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59005. // particles
  59006. var sp;
  59007. var currentCopy;
  59008. var idx = this.nbParticles;
  59009. for (var i = 0; i < nb; i++) {
  59010. var currentPos = this._positions.length;
  59011. var currentInd = this._indices.length;
  59012. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59013. if (this._updatable) {
  59014. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59015. sp.position.copyFrom(currentCopy.position);
  59016. sp.rotation.copyFrom(currentCopy.rotation);
  59017. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59018. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59019. }
  59020. if (currentCopy.color && sp.color) {
  59021. sp.color.copyFrom(currentCopy.color);
  59022. }
  59023. sp.scaling.copyFrom(currentCopy.scaling);
  59024. sp.uvs.copyFrom(currentCopy.uvs);
  59025. }
  59026. this._index += shape.length;
  59027. idx++;
  59028. }
  59029. this.nbParticles += nb;
  59030. this._shapeCounter++;
  59031. return this._shapeCounter - 1;
  59032. };
  59033. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59034. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59035. this._resetCopy();
  59036. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59037. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59038. }
  59039. if (this._copy.rotationQuaternion) {
  59040. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59041. }
  59042. else {
  59043. this._yaw = this._copy.rotation.y;
  59044. this._pitch = this._copy.rotation.x;
  59045. this._roll = this._copy.rotation.z;
  59046. this._quaternionRotationYPR();
  59047. }
  59048. this._quaternionToRotationMatrix();
  59049. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59050. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59051. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59052. if (this._copy.translateFromPivot) {
  59053. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59054. }
  59055. else {
  59056. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59057. }
  59058. this._shape = particle._model._shape;
  59059. for (var pt = 0; pt < this._shape.length; pt++) {
  59060. this._vertex.x = this._shape[pt].x;
  59061. this._vertex.y = this._shape[pt].y;
  59062. this._vertex.z = this._shape[pt].z;
  59063. if (particle._model._vertexFunction) {
  59064. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59065. }
  59066. this._vertex.x *= this._copy.scaling.x;
  59067. this._vertex.y *= this._copy.scaling.y;
  59068. this._vertex.z *= this._copy.scaling.z;
  59069. this._vertex.x -= this._scaledPivot.x;
  59070. this._vertex.y -= this._scaledPivot.y;
  59071. this._vertex.z -= this._scaledPivot.z;
  59072. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59073. this._rotated.addInPlace(this._pivotBackTranslation);
  59074. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59075. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59076. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59077. }
  59078. particle.position.x = 0.0;
  59079. particle.position.y = 0.0;
  59080. particle.position.z = 0.0;
  59081. particle.rotation.x = 0.0;
  59082. particle.rotation.y = 0.0;
  59083. particle.rotation.z = 0.0;
  59084. particle.rotationQuaternion = null;
  59085. particle.scaling.x = 1.0;
  59086. particle.scaling.y = 1.0;
  59087. particle.scaling.z = 1.0;
  59088. particle.uvs.x = 0.0;
  59089. particle.uvs.y = 0.0;
  59090. particle.uvs.z = 1.0;
  59091. particle.uvs.w = 1.0;
  59092. particle.pivot.x = 0.0;
  59093. particle.pivot.y = 0.0;
  59094. particle.pivot.z = 0.0;
  59095. particle.translateFromPivot = false;
  59096. particle.parentId = null;
  59097. };
  59098. /**
  59099. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59100. * @returns the SPS.
  59101. */
  59102. SolidParticleSystem.prototype.rebuildMesh = function () {
  59103. for (var p = 0; p < this.particles.length; p++) {
  59104. this._rebuildParticle(this.particles[p]);
  59105. }
  59106. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59107. return this;
  59108. };
  59109. /**
  59110. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59111. * This method calls `updateParticle()` for each particle of the SPS.
  59112. * For an animated SPS, it is usually called within the render loop.
  59113. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59114. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59115. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59116. * @returns the SPS.
  59117. */
  59118. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59119. if (start === void 0) { start = 0; }
  59120. if (end === void 0) { end = this.nbParticles - 1; }
  59121. if (update === void 0) { update = true; }
  59122. if (!this._updatable) {
  59123. return this;
  59124. }
  59125. // custom beforeUpdate
  59126. this.beforeUpdateParticles(start, end, update);
  59127. this._cam_axisX.x = 1.0;
  59128. this._cam_axisX.y = 0.0;
  59129. this._cam_axisX.z = 0.0;
  59130. this._cam_axisY.x = 0.0;
  59131. this._cam_axisY.y = 1.0;
  59132. this._cam_axisY.z = 0.0;
  59133. this._cam_axisZ.x = 0.0;
  59134. this._cam_axisZ.y = 0.0;
  59135. this._cam_axisZ.z = 1.0;
  59136. // cases when the World Matrix is to be computed first
  59137. if (this.billboard || this._depthSort) {
  59138. this.mesh.computeWorldMatrix(true);
  59139. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59140. }
  59141. // if the particles will always face the camera
  59142. if (this.billboard) {
  59143. // compute the camera position and un-rotate it by the current mesh rotation
  59144. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59145. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59146. this._cam_axisZ.normalize();
  59147. // same for camera up vector extracted from the cam view matrix
  59148. var view = this._camera.getViewMatrix(true);
  59149. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59150. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59151. this._cam_axisY.normalize();
  59152. this._cam_axisX.normalize();
  59153. }
  59154. // if depthSort, compute the camera global position in the mesh local system
  59155. if (this._depthSort) {
  59156. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59157. }
  59158. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59159. var idx = 0; // current position index in the global array positions32
  59160. var index = 0; // position start index in the global array positions32 of the current particle
  59161. var colidx = 0; // current color index in the global array colors32
  59162. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59163. var uvidx = 0; // current uv index in the global array uvs32
  59164. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59165. var pt = 0; // current index in the particle model shape
  59166. if (this.mesh.isFacetDataEnabled) {
  59167. this._computeBoundingBox = true;
  59168. }
  59169. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59170. if (this._computeBoundingBox) {
  59171. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59172. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59173. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59174. }
  59175. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59176. if (this.mesh._boundingInfo) {
  59177. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59178. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59179. }
  59180. }
  59181. }
  59182. // particle loop
  59183. index = this.particles[start]._pos;
  59184. var vpos = (index / 3) | 0;
  59185. colorIndex = vpos * 4;
  59186. uvIndex = vpos * 2;
  59187. for (var p = start; p <= end; p++) {
  59188. this._particle = this.particles[p];
  59189. this._shape = this._particle._model._shape;
  59190. this._shapeUV = this._particle._model._shapeUV;
  59191. // call to custom user function to update the particle properties
  59192. this.updateParticle(this._particle);
  59193. // camera-particle distance for depth sorting
  59194. if (this._depthSort && this._depthSortParticles) {
  59195. var dsp = this.depthSortedParticles[p];
  59196. dsp.ind = this._particle._ind;
  59197. dsp.indicesLength = this._particle._model._indicesLength;
  59198. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59199. }
  59200. // skip the computations for inactive or already invisible particles
  59201. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59202. // increment indexes for the next particle
  59203. pt = this._shape.length;
  59204. index += pt * 3;
  59205. colorIndex += pt * 4;
  59206. uvIndex += pt * 2;
  59207. continue;
  59208. }
  59209. if (this._particle.isVisible) {
  59210. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59211. this._particleHasParent = (this._particle.parentId !== null);
  59212. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59213. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59214. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59215. // particle rotation matrix
  59216. if (this.billboard) {
  59217. this._particle.rotation.x = 0.0;
  59218. this._particle.rotation.y = 0.0;
  59219. }
  59220. if (this._computeParticleRotation || this.billboard) {
  59221. if (this._particle.rotationQuaternion) {
  59222. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59223. }
  59224. else {
  59225. this._yaw = this._particle.rotation.y;
  59226. this._pitch = this._particle.rotation.x;
  59227. this._roll = this._particle.rotation.z;
  59228. this._quaternionRotationYPR();
  59229. }
  59230. this._quaternionToRotationMatrix();
  59231. }
  59232. if (this._particleHasParent) {
  59233. this._parent = this.particles[this._particle.parentId];
  59234. 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];
  59235. 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];
  59236. 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];
  59237. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59238. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59239. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59240. if (this._computeParticleRotation || this.billboard) {
  59241. 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];
  59242. 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];
  59243. 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];
  59244. 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];
  59245. 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];
  59246. 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];
  59247. 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];
  59248. 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];
  59249. 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];
  59250. }
  59251. }
  59252. else {
  59253. this._particle._globalPosition.x = this._particle.position.x;
  59254. this._particle._globalPosition.y = this._particle.position.y;
  59255. this._particle._globalPosition.z = this._particle.position.z;
  59256. if (this._computeParticleRotation || this.billboard) {
  59257. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59258. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59259. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59260. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59261. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59262. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59263. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59264. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59265. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59266. }
  59267. }
  59268. if (this._particle.translateFromPivot) {
  59269. this._pivotBackTranslation.x = 0.0;
  59270. this._pivotBackTranslation.y = 0.0;
  59271. this._pivotBackTranslation.z = 0.0;
  59272. }
  59273. else {
  59274. this._pivotBackTranslation.x = this._scaledPivot.x;
  59275. this._pivotBackTranslation.y = this._scaledPivot.y;
  59276. this._pivotBackTranslation.z = this._scaledPivot.z;
  59277. }
  59278. // particle vertex loop
  59279. for (pt = 0; pt < this._shape.length; pt++) {
  59280. idx = index + pt * 3;
  59281. colidx = colorIndex + pt * 4;
  59282. uvidx = uvIndex + pt * 2;
  59283. this._vertex.x = this._shape[pt].x;
  59284. this._vertex.y = this._shape[pt].y;
  59285. this._vertex.z = this._shape[pt].z;
  59286. if (this._computeParticleVertex) {
  59287. this.updateParticleVertex(this._particle, this._vertex, pt);
  59288. }
  59289. // positions
  59290. this._vertex.x *= this._particle.scaling.x;
  59291. this._vertex.y *= this._particle.scaling.y;
  59292. this._vertex.z *= this._particle.scaling.z;
  59293. this._vertex.x -= this._scaledPivot.x;
  59294. this._vertex.y -= this._scaledPivot.y;
  59295. this._vertex.z -= this._scaledPivot.z;
  59296. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59297. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59298. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59299. this._rotated.x += this._pivotBackTranslation.x;
  59300. this._rotated.y += this._pivotBackTranslation.y;
  59301. this._rotated.z += this._pivotBackTranslation.z;
  59302. 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;
  59303. 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;
  59304. 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;
  59305. if (this._computeBoundingBox) {
  59306. if (this._positions32[idx] < this._minimum.x) {
  59307. this._minimum.x = this._positions32[idx];
  59308. }
  59309. if (this._positions32[idx] > this._maximum.x) {
  59310. this._maximum.x = this._positions32[idx];
  59311. }
  59312. if (this._positions32[idx + 1] < this._minimum.y) {
  59313. this._minimum.y = this._positions32[idx + 1];
  59314. }
  59315. if (this._positions32[idx + 1] > this._maximum.y) {
  59316. this._maximum.y = this._positions32[idx + 1];
  59317. }
  59318. if (this._positions32[idx + 2] < this._minimum.z) {
  59319. this._minimum.z = this._positions32[idx + 2];
  59320. }
  59321. if (this._positions32[idx + 2] > this._maximum.z) {
  59322. this._maximum.z = this._positions32[idx + 2];
  59323. }
  59324. }
  59325. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59326. if (!this._computeParticleVertex) {
  59327. this._normal.x = this._fixedNormal32[idx];
  59328. this._normal.y = this._fixedNormal32[idx + 1];
  59329. this._normal.z = this._fixedNormal32[idx + 2];
  59330. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59331. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59332. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59333. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59334. 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;
  59335. 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;
  59336. }
  59337. if (this._computeParticleColor && this._particle.color) {
  59338. this._colors32[colidx] = this._particle.color.r;
  59339. this._colors32[colidx + 1] = this._particle.color.g;
  59340. this._colors32[colidx + 2] = this._particle.color.b;
  59341. this._colors32[colidx + 3] = this._particle.color.a;
  59342. }
  59343. if (this._computeParticleTexture) {
  59344. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59345. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59346. }
  59347. }
  59348. }
  59349. // particle just set invisible : scaled to zero and positioned at the origin
  59350. else {
  59351. this._particle._stillInvisible = true; // mark the particle as invisible
  59352. for (pt = 0; pt < this._shape.length; pt++) {
  59353. idx = index + pt * 3;
  59354. colidx = colorIndex + pt * 4;
  59355. uvidx = uvIndex + pt * 2;
  59356. this._positions32[idx] = 0.0;
  59357. this._positions32[idx + 1] = 0.0;
  59358. this._positions32[idx + 2] = 0.0;
  59359. this._normals32[idx] = 0.0;
  59360. this._normals32[idx + 1] = 0.0;
  59361. this._normals32[idx + 2] = 0.0;
  59362. if (this._computeParticleColor && this._particle.color) {
  59363. this._colors32[colidx] = this._particle.color.r;
  59364. this._colors32[colidx + 1] = this._particle.color.g;
  59365. this._colors32[colidx + 2] = this._particle.color.b;
  59366. this._colors32[colidx + 3] = this._particle.color.a;
  59367. }
  59368. if (this._computeParticleTexture) {
  59369. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59370. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59371. }
  59372. }
  59373. }
  59374. // if the particle intersections must be computed : update the bbInfo
  59375. if (this._particlesIntersect) {
  59376. var bInfo = this._particle._boundingInfo;
  59377. var bBox = bInfo.boundingBox;
  59378. var bSphere = bInfo.boundingSphere;
  59379. if (!this._bSphereOnly) {
  59380. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59381. for (var b = 0; b < bBox.vectors.length; b++) {
  59382. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59383. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59384. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59385. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59386. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59387. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59388. 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;
  59389. 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;
  59390. 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;
  59391. }
  59392. bBox._update(this.mesh._worldMatrix);
  59393. }
  59394. // place and scale the particle bouding sphere in the SPS local system, then update it
  59395. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59396. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59397. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59398. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59399. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59400. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59401. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59402. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59403. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59404. 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));
  59405. bSphere._update(this.mesh._worldMatrix);
  59406. }
  59407. // increment indexes for the next particle
  59408. index = idx + 3;
  59409. colorIndex = colidx + 4;
  59410. uvIndex = uvidx + 2;
  59411. }
  59412. // if the VBO must be updated
  59413. if (update) {
  59414. if (this._computeParticleColor) {
  59415. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59416. }
  59417. if (this._computeParticleTexture) {
  59418. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59419. }
  59420. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59421. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59422. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59423. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59424. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59425. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59426. for (var i = 0; i < this._normals32.length; i++) {
  59427. this._fixedNormal32[i] = this._normals32[i];
  59428. }
  59429. }
  59430. if (!this.mesh.areNormalsFrozen) {
  59431. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59432. }
  59433. }
  59434. if (this._depthSort && this._depthSortParticles) {
  59435. this.depthSortedParticles.sort(this._depthSortFunction);
  59436. var dspl = this.depthSortedParticles.length;
  59437. var sorted = 0;
  59438. var lind = 0;
  59439. var sind = 0;
  59440. var sid = 0;
  59441. for (sorted = 0; sorted < dspl; sorted++) {
  59442. lind = this.depthSortedParticles[sorted].indicesLength;
  59443. sind = this.depthSortedParticles[sorted].ind;
  59444. for (var i = 0; i < lind; i++) {
  59445. this._indices32[sid] = this._indices[sind + i];
  59446. sid++;
  59447. }
  59448. }
  59449. this.mesh.updateIndices(this._indices32);
  59450. }
  59451. }
  59452. if (this._computeBoundingBox) {
  59453. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59454. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59455. }
  59456. this.afterUpdateParticles(start, end, update);
  59457. return this;
  59458. };
  59459. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59460. this._halfroll = this._roll * 0.5;
  59461. this._halfpitch = this._pitch * 0.5;
  59462. this._halfyaw = this._yaw * 0.5;
  59463. this._sinRoll = Math.sin(this._halfroll);
  59464. this._cosRoll = Math.cos(this._halfroll);
  59465. this._sinPitch = Math.sin(this._halfpitch);
  59466. this._cosPitch = Math.cos(this._halfpitch);
  59467. this._sinYaw = Math.sin(this._halfyaw);
  59468. this._cosYaw = Math.cos(this._halfyaw);
  59469. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59470. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59471. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59472. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59473. };
  59474. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59475. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59476. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59477. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59478. this._rotMatrix.m[3] = 0;
  59479. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59480. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59481. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59482. this._rotMatrix.m[7] = 0;
  59483. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59484. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59485. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59486. this._rotMatrix.m[11] = 0;
  59487. this._rotMatrix.m[12] = 0;
  59488. this._rotMatrix.m[13] = 0;
  59489. this._rotMatrix.m[14] = 0;
  59490. this._rotMatrix.m[15] = 1.0;
  59491. };
  59492. /**
  59493. * Disposes the SPS.
  59494. */
  59495. SolidParticleSystem.prototype.dispose = function () {
  59496. this.mesh.dispose();
  59497. this.vars = null;
  59498. // drop references to internal big arrays for the GC
  59499. this._positions = null;
  59500. this._indices = null;
  59501. this._normals = null;
  59502. this._uvs = null;
  59503. this._colors = null;
  59504. this._indices32 = null;
  59505. this._positions32 = null;
  59506. this._normals32 = null;
  59507. this._fixedNormal32 = null;
  59508. this._uvs32 = null;
  59509. this._colors32 = null;
  59510. this.pickedParticles = null;
  59511. };
  59512. /**
  59513. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59514. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59515. * @returns the SPS.
  59516. */
  59517. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59518. if (!this._isVisibilityBoxLocked) {
  59519. this.mesh.refreshBoundingInfo();
  59520. }
  59521. return this;
  59522. };
  59523. /**
  59524. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59525. * @param size the size (float) of the visibility box
  59526. * note : this doesn't lock the SPS mesh bounding box.
  59527. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59528. */
  59529. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59530. var vis = size / 2;
  59531. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59532. };
  59533. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59534. /**
  59535. * Gets whether the SPS as always visible or not
  59536. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59537. */
  59538. get: function () {
  59539. return this._alwaysVisible;
  59540. },
  59541. /**
  59542. * Sets the SPS as always visible or not
  59543. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59544. */
  59545. set: function (val) {
  59546. this._alwaysVisible = val;
  59547. this.mesh.alwaysSelectAsActiveMesh = val;
  59548. },
  59549. enumerable: true,
  59550. configurable: true
  59551. });
  59552. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59553. /**
  59554. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59556. */
  59557. get: function () {
  59558. return this._isVisibilityBoxLocked;
  59559. },
  59560. /**
  59561. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59562. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59563. */
  59564. set: function (val) {
  59565. this._isVisibilityBoxLocked = val;
  59566. var boundingInfo = this.mesh.getBoundingInfo();
  59567. boundingInfo.isLocked = val;
  59568. },
  59569. enumerable: true,
  59570. configurable: true
  59571. });
  59572. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59573. /**
  59574. * Gets if `setParticles()` computes the particle rotations or not.
  59575. * Default value : true. The SPS is faster when it's set to false.
  59576. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59577. */
  59578. get: function () {
  59579. return this._computeParticleRotation;
  59580. },
  59581. /**
  59582. * Tells to `setParticles()` to compute the particle rotations or not.
  59583. * Default value : true. The SPS is faster when it's set to false.
  59584. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59585. */
  59586. set: function (val) {
  59587. this._computeParticleRotation = val;
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59593. /**
  59594. * Gets if `setParticles()` computes the particle colors or not.
  59595. * Default value : true. The SPS is faster when it's set to false.
  59596. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59597. */
  59598. get: function () {
  59599. return this._computeParticleColor;
  59600. },
  59601. /**
  59602. * Tells to `setParticles()` to compute the particle colors or not.
  59603. * Default value : true. The SPS is faster when it's set to false.
  59604. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59605. */
  59606. set: function (val) {
  59607. this._computeParticleColor = val;
  59608. },
  59609. enumerable: true,
  59610. configurable: true
  59611. });
  59612. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59613. /**
  59614. * Gets if `setParticles()` computes the particle textures or not.
  59615. * Default value : true. The SPS is faster when it's set to false.
  59616. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59617. */
  59618. get: function () {
  59619. return this._computeParticleTexture;
  59620. },
  59621. set: function (val) {
  59622. this._computeParticleTexture = val;
  59623. },
  59624. enumerable: true,
  59625. configurable: true
  59626. });
  59627. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59628. /**
  59629. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59630. * Default value : false. The SPS is faster when it's set to false.
  59631. * Note : the particle custom vertex positions aren't stored values.
  59632. */
  59633. get: function () {
  59634. return this._computeParticleVertex;
  59635. },
  59636. /**
  59637. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59638. * Default value : false. The SPS is faster when it's set to false.
  59639. * Note : the particle custom vertex positions aren't stored values.
  59640. */
  59641. set: function (val) {
  59642. this._computeParticleVertex = val;
  59643. },
  59644. enumerable: true,
  59645. configurable: true
  59646. });
  59647. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59648. /**
  59649. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59650. */
  59651. get: function () {
  59652. return this._computeBoundingBox;
  59653. },
  59654. /**
  59655. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59656. */
  59657. set: function (val) {
  59658. this._computeBoundingBox = val;
  59659. },
  59660. enumerable: true,
  59661. configurable: true
  59662. });
  59663. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59664. /**
  59665. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59666. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59667. * Default : `true`
  59668. */
  59669. get: function () {
  59670. return this._depthSortParticles;
  59671. },
  59672. /**
  59673. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59674. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59675. * Default : `true`
  59676. */
  59677. set: function (val) {
  59678. this._depthSortParticles = val;
  59679. },
  59680. enumerable: true,
  59681. configurable: true
  59682. });
  59683. // =======================================================================
  59684. // Particle behavior logic
  59685. // these following methods may be overwritten by the user to fit his needs
  59686. /**
  59687. * This function does nothing. It may be overwritten to set all the particle first values.
  59688. * The SPS doesn't call this function, you may have to call it by your own.
  59689. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59690. */
  59691. SolidParticleSystem.prototype.initParticles = function () {
  59692. };
  59693. /**
  59694. * This function does nothing. It may be overwritten to recycle a particle.
  59695. * The SPS doesn't call this function, you may have to call it by your own.
  59696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59697. * @param particle The particle to recycle
  59698. * @returns the recycled particle
  59699. */
  59700. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59701. return particle;
  59702. };
  59703. /**
  59704. * Updates a particle : this function should be overwritten by the user.
  59705. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59706. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59707. * @example : just set a particle position or velocity and recycle conditions
  59708. * @param particle The particle to update
  59709. * @returns the updated particle
  59710. */
  59711. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59712. return particle;
  59713. };
  59714. /**
  59715. * Updates a vertex of a particle : it can be overwritten by the user.
  59716. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59717. * @param particle the current particle
  59718. * @param vertex the current index of the current particle
  59719. * @param pt the index of the current vertex in the particle shape
  59720. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59721. * @example : just set a vertex particle position
  59722. * @returns the updated vertex
  59723. */
  59724. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59725. return vertex;
  59726. };
  59727. /**
  59728. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59729. * This does nothing and may be overwritten by the user.
  59730. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59731. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59732. * @param update the boolean update value actually passed to setParticles()
  59733. */
  59734. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59735. };
  59736. /**
  59737. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59738. * This will be passed three parameters.
  59739. * This does nothing and may be overwritten by the user.
  59740. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59741. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59742. * @param update the boolean update value actually passed to setParticles()
  59743. */
  59744. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59745. };
  59746. return SolidParticleSystem;
  59747. }());
  59748. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59749. })(BABYLON || (BABYLON = {}));
  59750. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59751. var BABYLON;
  59752. (function (BABYLON) {
  59753. var ShaderMaterial = /** @class */ (function (_super) {
  59754. __extends(ShaderMaterial, _super);
  59755. function ShaderMaterial(name, scene, shaderPath, options) {
  59756. var _this = _super.call(this, name, scene) || this;
  59757. _this._textures = {};
  59758. _this._textureArrays = {};
  59759. _this._floats = {};
  59760. _this._ints = {};
  59761. _this._floatsArrays = {};
  59762. _this._colors3 = {};
  59763. _this._colors3Arrays = {};
  59764. _this._colors4 = {};
  59765. _this._vectors2 = {};
  59766. _this._vectors3 = {};
  59767. _this._vectors4 = {};
  59768. _this._matrices = {};
  59769. _this._matrices3x3 = {};
  59770. _this._matrices2x2 = {};
  59771. _this._vectors2Arrays = {};
  59772. _this._vectors3Arrays = {};
  59773. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59774. _this._shaderPath = shaderPath;
  59775. options.needAlphaBlending = options.needAlphaBlending || false;
  59776. options.needAlphaTesting = options.needAlphaTesting || false;
  59777. options.attributes = options.attributes || ["position", "normal", "uv"];
  59778. options.uniforms = options.uniforms || ["worldViewProjection"];
  59779. options.uniformBuffers = options.uniformBuffers || [];
  59780. options.samplers = options.samplers || [];
  59781. options.defines = options.defines || [];
  59782. _this._options = options;
  59783. return _this;
  59784. }
  59785. ShaderMaterial.prototype.getClassName = function () {
  59786. return "ShaderMaterial";
  59787. };
  59788. ShaderMaterial.prototype.needAlphaBlending = function () {
  59789. return this._options.needAlphaBlending;
  59790. };
  59791. ShaderMaterial.prototype.needAlphaTesting = function () {
  59792. return this._options.needAlphaTesting;
  59793. };
  59794. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59795. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59796. this._options.uniforms.push(uniformName);
  59797. }
  59798. };
  59799. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59800. if (this._options.samplers.indexOf(name) === -1) {
  59801. this._options.samplers.push(name);
  59802. }
  59803. this._textures[name] = texture;
  59804. return this;
  59805. };
  59806. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59807. if (this._options.samplers.indexOf(name) === -1) {
  59808. this._options.samplers.push(name);
  59809. }
  59810. this._checkUniform(name);
  59811. this._textureArrays[name] = textures;
  59812. return this;
  59813. };
  59814. ShaderMaterial.prototype.setFloat = function (name, value) {
  59815. this._checkUniform(name);
  59816. this._floats[name] = value;
  59817. return this;
  59818. };
  59819. ShaderMaterial.prototype.setInt = function (name, value) {
  59820. this._checkUniform(name);
  59821. this._ints[name] = value;
  59822. return this;
  59823. };
  59824. ShaderMaterial.prototype.setFloats = function (name, value) {
  59825. this._checkUniform(name);
  59826. this._floatsArrays[name] = value;
  59827. return this;
  59828. };
  59829. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59830. this._checkUniform(name);
  59831. this._colors3[name] = value;
  59832. return this;
  59833. };
  59834. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59835. this._checkUniform(name);
  59836. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59837. color.toArray(arr, arr.length);
  59838. return arr;
  59839. }, []);
  59840. return this;
  59841. };
  59842. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59843. this._checkUniform(name);
  59844. this._colors4[name] = value;
  59845. return this;
  59846. };
  59847. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59848. this._checkUniform(name);
  59849. this._vectors2[name] = value;
  59850. return this;
  59851. };
  59852. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59853. this._checkUniform(name);
  59854. this._vectors3[name] = value;
  59855. return this;
  59856. };
  59857. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59858. this._checkUniform(name);
  59859. this._vectors4[name] = value;
  59860. return this;
  59861. };
  59862. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59863. this._checkUniform(name);
  59864. this._matrices[name] = value;
  59865. return this;
  59866. };
  59867. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59868. this._checkUniform(name);
  59869. this._matrices3x3[name] = value;
  59870. return this;
  59871. };
  59872. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59873. this._checkUniform(name);
  59874. this._matrices2x2[name] = value;
  59875. return this;
  59876. };
  59877. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59878. this._checkUniform(name);
  59879. this._vectors2Arrays[name] = value;
  59880. return this;
  59881. };
  59882. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59883. this._checkUniform(name);
  59884. this._vectors3Arrays[name] = value;
  59885. return this;
  59886. };
  59887. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59888. if (!mesh) {
  59889. return true;
  59890. }
  59891. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59892. return false;
  59893. }
  59894. return false;
  59895. };
  59896. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59897. var scene = this.getScene();
  59898. var engine = scene.getEngine();
  59899. if (!this.checkReadyOnEveryCall) {
  59900. if (this._renderId === scene.getRenderId()) {
  59901. if (this._checkCache(scene, mesh, useInstances)) {
  59902. return true;
  59903. }
  59904. }
  59905. }
  59906. // Instances
  59907. var defines = [];
  59908. var attribs = [];
  59909. var fallbacks = new BABYLON.EffectFallbacks();
  59910. if (useInstances) {
  59911. defines.push("#define INSTANCES");
  59912. }
  59913. for (var index = 0; index < this._options.defines.length; index++) {
  59914. defines.push(this._options.defines[index]);
  59915. }
  59916. for (var index = 0; index < this._options.attributes.length; index++) {
  59917. attribs.push(this._options.attributes[index]);
  59918. }
  59919. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59920. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59921. defines.push("#define VERTEXCOLOR");
  59922. }
  59923. // Bones
  59924. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59927. if (mesh.numBoneInfluencers > 4) {
  59928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59930. }
  59931. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59932. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59933. fallbacks.addCPUSkinningFallback(0, mesh);
  59934. if (this._options.uniforms.indexOf("mBones") === -1) {
  59935. this._options.uniforms.push("mBones");
  59936. }
  59937. }
  59938. else {
  59939. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59940. }
  59941. // Textures
  59942. for (var name in this._textures) {
  59943. if (!this._textures[name].isReady()) {
  59944. return false;
  59945. }
  59946. }
  59947. // Alpha test
  59948. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59949. defines.push("#define ALPHATEST");
  59950. }
  59951. var previousEffect = this._effect;
  59952. var join = defines.join("\n");
  59953. this._effect = engine.createEffect(this._shaderPath, {
  59954. attributes: attribs,
  59955. uniformsNames: this._options.uniforms,
  59956. uniformBuffersNames: this._options.uniformBuffers,
  59957. samplers: this._options.samplers,
  59958. defines: join,
  59959. fallbacks: fallbacks,
  59960. onCompiled: this.onCompiled,
  59961. onError: this.onError
  59962. }, engine);
  59963. if (!this._effect.isReady()) {
  59964. return false;
  59965. }
  59966. if (previousEffect !== this._effect) {
  59967. scene.resetCachedMaterial();
  59968. }
  59969. this._renderId = scene.getRenderId();
  59970. return true;
  59971. };
  59972. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59973. var scene = this.getScene();
  59974. if (!this._effect) {
  59975. return;
  59976. }
  59977. if (this._options.uniforms.indexOf("world") !== -1) {
  59978. this._effect.setMatrix("world", world);
  59979. }
  59980. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59981. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59982. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59983. }
  59984. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59985. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59986. }
  59987. };
  59988. ShaderMaterial.prototype.bind = function (world, mesh) {
  59989. // Std values
  59990. this.bindOnlyWorldMatrix(world);
  59991. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59992. if (this._options.uniforms.indexOf("view") !== -1) {
  59993. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59994. }
  59995. if (this._options.uniforms.indexOf("projection") !== -1) {
  59996. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59997. }
  59998. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59999. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60000. }
  60001. // Bones
  60002. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60003. var name;
  60004. // Texture
  60005. for (name in this._textures) {
  60006. this._effect.setTexture(name, this._textures[name]);
  60007. }
  60008. // Texture arrays
  60009. for (name in this._textureArrays) {
  60010. this._effect.setTextureArray(name, this._textureArrays[name]);
  60011. }
  60012. // Int
  60013. for (name in this._ints) {
  60014. this._effect.setInt(name, this._ints[name]);
  60015. }
  60016. // Float
  60017. for (name in this._floats) {
  60018. this._effect.setFloat(name, this._floats[name]);
  60019. }
  60020. // Floats
  60021. for (name in this._floatsArrays) {
  60022. this._effect.setArray(name, this._floatsArrays[name]);
  60023. }
  60024. // Color3
  60025. for (name in this._colors3) {
  60026. this._effect.setColor3(name, this._colors3[name]);
  60027. }
  60028. for (name in this._colors3Arrays) {
  60029. this._effect.setArray3(name, this._colors3Arrays[name]);
  60030. }
  60031. // Color4
  60032. for (name in this._colors4) {
  60033. var color = this._colors4[name];
  60034. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60035. }
  60036. // Vector2
  60037. for (name in this._vectors2) {
  60038. this._effect.setVector2(name, this._vectors2[name]);
  60039. }
  60040. // Vector3
  60041. for (name in this._vectors3) {
  60042. this._effect.setVector3(name, this._vectors3[name]);
  60043. }
  60044. // Vector4
  60045. for (name in this._vectors4) {
  60046. this._effect.setVector4(name, this._vectors4[name]);
  60047. }
  60048. // Matrix
  60049. for (name in this._matrices) {
  60050. this._effect.setMatrix(name, this._matrices[name]);
  60051. }
  60052. // Matrix 3x3
  60053. for (name in this._matrices3x3) {
  60054. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60055. }
  60056. // Matrix 2x2
  60057. for (name in this._matrices2x2) {
  60058. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60059. }
  60060. // Vector2Array
  60061. for (name in this._vectors2Arrays) {
  60062. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60063. }
  60064. // Vector3Array
  60065. for (name in this._vectors3Arrays) {
  60066. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60067. }
  60068. }
  60069. this._afterBind(mesh);
  60070. };
  60071. ShaderMaterial.prototype.getActiveTextures = function () {
  60072. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60073. for (var name in this._textures) {
  60074. activeTextures.push(this._textures[name]);
  60075. }
  60076. for (var name in this._textureArrays) {
  60077. var array = this._textureArrays[name];
  60078. for (var index = 0; index < array.length; index++) {
  60079. activeTextures.push(array[index]);
  60080. }
  60081. }
  60082. return activeTextures;
  60083. };
  60084. ShaderMaterial.prototype.hasTexture = function (texture) {
  60085. if (_super.prototype.hasTexture.call(this, texture)) {
  60086. return true;
  60087. }
  60088. for (var name in this._textures) {
  60089. if (this._textures[name] === texture) {
  60090. return true;
  60091. }
  60092. }
  60093. for (var name in this._textureArrays) {
  60094. var array = this._textureArrays[name];
  60095. for (var index = 0; index < array.length; index++) {
  60096. if (array[index] === texture) {
  60097. return true;
  60098. }
  60099. }
  60100. }
  60101. return false;
  60102. };
  60103. ShaderMaterial.prototype.clone = function (name) {
  60104. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60105. return newShaderMaterial;
  60106. };
  60107. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60108. if (forceDisposeTextures) {
  60109. var name;
  60110. for (name in this._textures) {
  60111. this._textures[name].dispose();
  60112. }
  60113. for (name in this._textureArrays) {
  60114. var array = this._textureArrays[name];
  60115. for (var index = 0; index < array.length; index++) {
  60116. array[index].dispose();
  60117. }
  60118. }
  60119. }
  60120. this._textures = {};
  60121. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60122. };
  60123. ShaderMaterial.prototype.serialize = function () {
  60124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60125. serializationObject.customType = "BABYLON.ShaderMaterial";
  60126. serializationObject.options = this._options;
  60127. serializationObject.shaderPath = this._shaderPath;
  60128. var name;
  60129. // Texture
  60130. serializationObject.textures = {};
  60131. for (name in this._textures) {
  60132. serializationObject.textures[name] = this._textures[name].serialize();
  60133. }
  60134. // Texture arrays
  60135. serializationObject.textureArrays = {};
  60136. for (name in this._textureArrays) {
  60137. serializationObject.textureArrays[name] = [];
  60138. var array = this._textureArrays[name];
  60139. for (var index = 0; index < array.length; index++) {
  60140. serializationObject.textureArrays[name].push(array[index].serialize());
  60141. }
  60142. }
  60143. // Float
  60144. serializationObject.floats = {};
  60145. for (name in this._floats) {
  60146. serializationObject.floats[name] = this._floats[name];
  60147. }
  60148. // Float s
  60149. serializationObject.FloatArrays = {};
  60150. for (name in this._floatsArrays) {
  60151. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60152. }
  60153. // Color3
  60154. serializationObject.colors3 = {};
  60155. for (name in this._colors3) {
  60156. serializationObject.colors3[name] = this._colors3[name].asArray();
  60157. }
  60158. // Color3 array
  60159. serializationObject.colors3Arrays = {};
  60160. for (name in this._colors3Arrays) {
  60161. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60162. }
  60163. // Color4
  60164. serializationObject.colors4 = {};
  60165. for (name in this._colors4) {
  60166. serializationObject.colors4[name] = this._colors4[name].asArray();
  60167. }
  60168. // Vector2
  60169. serializationObject.vectors2 = {};
  60170. for (name in this._vectors2) {
  60171. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60172. }
  60173. // Vector3
  60174. serializationObject.vectors3 = {};
  60175. for (name in this._vectors3) {
  60176. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60177. }
  60178. // Vector4
  60179. serializationObject.vectors4 = {};
  60180. for (name in this._vectors4) {
  60181. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60182. }
  60183. // Matrix
  60184. serializationObject.matrices = {};
  60185. for (name in this._matrices) {
  60186. serializationObject.matrices[name] = this._matrices[name].asArray();
  60187. }
  60188. // Matrix 3x3
  60189. serializationObject.matrices3x3 = {};
  60190. for (name in this._matrices3x3) {
  60191. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60192. }
  60193. // Matrix 2x2
  60194. serializationObject.matrices2x2 = {};
  60195. for (name in this._matrices2x2) {
  60196. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60197. }
  60198. // Vector2Array
  60199. serializationObject.vectors2Arrays = {};
  60200. for (name in this._vectors2Arrays) {
  60201. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60202. }
  60203. // Vector3Array
  60204. serializationObject.vectors3Arrays = {};
  60205. for (name in this._vectors3Arrays) {
  60206. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60207. }
  60208. return serializationObject;
  60209. };
  60210. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60211. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60212. var name;
  60213. // Texture
  60214. for (name in source.textures) {
  60215. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60216. }
  60217. // Texture arrays
  60218. for (name in source.textureArrays) {
  60219. var array = source.textureArrays[name];
  60220. var textureArray = new Array();
  60221. for (var index = 0; index < array.length; index++) {
  60222. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60223. }
  60224. material.setTextureArray(name, textureArray);
  60225. }
  60226. // Float
  60227. for (name in source.floats) {
  60228. material.setFloat(name, source.floats[name]);
  60229. }
  60230. // Float s
  60231. for (name in source.floatsArrays) {
  60232. material.setFloats(name, source.floatsArrays[name]);
  60233. }
  60234. // Color3
  60235. for (name in source.colors3) {
  60236. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60237. }
  60238. // Color3 arrays
  60239. for (name in source.colors3Arrays) {
  60240. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60241. if (i % 3 === 0) {
  60242. arr.push([num]);
  60243. }
  60244. else {
  60245. arr[arr.length - 1].push(num);
  60246. }
  60247. return arr;
  60248. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60249. material.setColor3Array(name, colors);
  60250. }
  60251. // Color4
  60252. for (name in source.colors4) {
  60253. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60254. }
  60255. // Vector2
  60256. for (name in source.vectors2) {
  60257. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60258. }
  60259. // Vector3
  60260. for (name in source.vectors3) {
  60261. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60262. }
  60263. // Vector4
  60264. for (name in source.vectors4) {
  60265. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60266. }
  60267. // Matrix
  60268. for (name in source.matrices) {
  60269. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60270. }
  60271. // Matrix 3x3
  60272. for (name in source.matrices3x3) {
  60273. material.setMatrix3x3(name, source.matrices3x3[name]);
  60274. }
  60275. // Matrix 2x2
  60276. for (name in source.matrices2x2) {
  60277. material.setMatrix2x2(name, source.matrices2x2[name]);
  60278. }
  60279. // Vector2Array
  60280. for (name in source.vectors2Arrays) {
  60281. material.setArray2(name, source.vectors2Arrays[name]);
  60282. }
  60283. // Vector3Array
  60284. for (name in source.vectors3Arrays) {
  60285. material.setArray3(name, source.vectors3Arrays[name]);
  60286. }
  60287. return material;
  60288. };
  60289. return ShaderMaterial;
  60290. }(BABYLON.Material));
  60291. BABYLON.ShaderMaterial = ShaderMaterial;
  60292. })(BABYLON || (BABYLON = {}));
  60293. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60294. var BABYLON;
  60295. (function (BABYLON) {
  60296. var GroundMesh = /** @class */ (function (_super) {
  60297. __extends(GroundMesh, _super);
  60298. function GroundMesh(name, scene) {
  60299. var _this = _super.call(this, name, scene) || this;
  60300. _this.generateOctree = false;
  60301. return _this;
  60302. }
  60303. GroundMesh.prototype.getClassName = function () {
  60304. return "GroundMesh";
  60305. };
  60306. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60307. get: function () {
  60308. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60309. },
  60310. enumerable: true,
  60311. configurable: true
  60312. });
  60313. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60314. get: function () {
  60315. return this._subdivisionsX;
  60316. },
  60317. enumerable: true,
  60318. configurable: true
  60319. });
  60320. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60321. get: function () {
  60322. return this._subdivisionsY;
  60323. },
  60324. enumerable: true,
  60325. configurable: true
  60326. });
  60327. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60328. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60329. this._subdivisionsX = chunksCount;
  60330. this._subdivisionsY = chunksCount;
  60331. this.subdivide(chunksCount);
  60332. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60333. };
  60334. /**
  60335. * Returns a height (y) value in the Worl system :
  60336. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60337. * Returns the ground y position if (x, z) are outside the ground surface.
  60338. */
  60339. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60340. var world = this.getWorldMatrix();
  60341. var invMat = BABYLON.Tmp.Matrix[5];
  60342. world.invertToRef(invMat);
  60343. var tmpVect = BABYLON.Tmp.Vector3[8];
  60344. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60345. x = tmpVect.x;
  60346. z = tmpVect.z;
  60347. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60348. return this.position.y;
  60349. }
  60350. if (!this._heightQuads || this._heightQuads.length == 0) {
  60351. this._initHeightQuads();
  60352. this._computeHeightQuads();
  60353. }
  60354. var facet = this._getFacetAt(x, z);
  60355. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60356. // return y in the World system
  60357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60358. return tmpVect.y;
  60359. };
  60360. /**
  60361. * Returns a normalized vector (Vector3) orthogonal to the ground
  60362. * at the ground coordinates (x, z) expressed in the World system.
  60363. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60364. */
  60365. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60366. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60367. this.getNormalAtCoordinatesToRef(x, z, normal);
  60368. return normal;
  60369. };
  60370. /**
  60371. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60372. * at the ground coordinates (x, z) expressed in the World system.
  60373. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60374. * Returns the GroundMesh.
  60375. */
  60376. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60377. var world = this.getWorldMatrix();
  60378. var tmpMat = BABYLON.Tmp.Matrix[5];
  60379. world.invertToRef(tmpMat);
  60380. var tmpVect = BABYLON.Tmp.Vector3[8];
  60381. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60382. x = tmpVect.x;
  60383. z = tmpVect.z;
  60384. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60385. return this;
  60386. }
  60387. if (!this._heightQuads || this._heightQuads.length == 0) {
  60388. this._initHeightQuads();
  60389. this._computeHeightQuads();
  60390. }
  60391. var facet = this._getFacetAt(x, z);
  60392. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60393. return this;
  60394. };
  60395. /**
  60396. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60397. * if the ground has been updated.
  60398. * This can be used in the render loop.
  60399. * Returns the GroundMesh.
  60400. */
  60401. GroundMesh.prototype.updateCoordinateHeights = function () {
  60402. if (!this._heightQuads || this._heightQuads.length == 0) {
  60403. this._initHeightQuads();
  60404. }
  60405. this._computeHeightQuads();
  60406. return this;
  60407. };
  60408. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60409. GroundMesh.prototype._getFacetAt = function (x, z) {
  60410. // retrieve col and row from x, z coordinates in the ground local system
  60411. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60412. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60413. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60414. var facet;
  60415. if (z < quad.slope.x * x + quad.slope.y) {
  60416. facet = quad.facet1;
  60417. }
  60418. else {
  60419. facet = quad.facet2;
  60420. }
  60421. return facet;
  60422. };
  60423. // Creates and populates the heightMap array with "facet" elements :
  60424. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60425. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60426. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60427. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60428. // Returns the GroundMesh.
  60429. GroundMesh.prototype._initHeightQuads = function () {
  60430. var subdivisionsX = this._subdivisionsX;
  60431. var subdivisionsY = this._subdivisionsY;
  60432. this._heightQuads = new Array();
  60433. for (var row = 0; row < subdivisionsY; row++) {
  60434. for (var col = 0; col < subdivisionsX; col++) {
  60435. 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) };
  60436. this._heightQuads[row * subdivisionsX + col] = quad;
  60437. }
  60438. }
  60439. return this;
  60440. };
  60441. // Compute each quad element values and update the the heightMap array :
  60442. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60443. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60444. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60445. // Returns the GroundMesh.
  60446. GroundMesh.prototype._computeHeightQuads = function () {
  60447. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60448. if (!positions) {
  60449. return this;
  60450. }
  60451. var v1 = BABYLON.Tmp.Vector3[3];
  60452. var v2 = BABYLON.Tmp.Vector3[2];
  60453. var v3 = BABYLON.Tmp.Vector3[1];
  60454. var v4 = BABYLON.Tmp.Vector3[0];
  60455. var v1v2 = BABYLON.Tmp.Vector3[4];
  60456. var v1v3 = BABYLON.Tmp.Vector3[5];
  60457. var v1v4 = BABYLON.Tmp.Vector3[6];
  60458. var norm1 = BABYLON.Tmp.Vector3[7];
  60459. var norm2 = BABYLON.Tmp.Vector3[8];
  60460. var i = 0;
  60461. var j = 0;
  60462. var k = 0;
  60463. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60464. var h = 0;
  60465. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60466. var d2 = 0;
  60467. var subdivisionsX = this._subdivisionsX;
  60468. var subdivisionsY = this._subdivisionsY;
  60469. for (var row = 0; row < subdivisionsY; row++) {
  60470. for (var col = 0; col < subdivisionsX; col++) {
  60471. i = col * 3;
  60472. j = row * (subdivisionsX + 1) * 3;
  60473. k = (row + 1) * (subdivisionsX + 1) * 3;
  60474. v1.x = positions[j + i];
  60475. v1.y = positions[j + i + 1];
  60476. v1.z = positions[j + i + 2];
  60477. v2.x = positions[j + i + 3];
  60478. v2.y = positions[j + i + 4];
  60479. v2.z = positions[j + i + 5];
  60480. v3.x = positions[k + i];
  60481. v3.y = positions[k + i + 1];
  60482. v3.z = positions[k + i + 2];
  60483. v4.x = positions[k + i + 3];
  60484. v4.y = positions[k + i + 4];
  60485. v4.z = positions[k + i + 5];
  60486. // 2D slope V1V4
  60487. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60488. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60489. // facet equations :
  60490. // we compute each facet normal vector
  60491. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60492. // we compute the value d by applying the equation to v1 which belongs to the plane
  60493. // then we store the facet equation in a Vector4
  60494. v2.subtractToRef(v1, v1v2);
  60495. v3.subtractToRef(v1, v1v3);
  60496. v4.subtractToRef(v1, v1v4);
  60497. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60498. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60499. norm1.normalize();
  60500. norm2.normalize();
  60501. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60502. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60503. var quad = this._heightQuads[row * subdivisionsX + col];
  60504. quad.slope.copyFromFloats(cd, h);
  60505. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60506. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60507. }
  60508. }
  60509. return this;
  60510. };
  60511. GroundMesh.prototype.serialize = function (serializationObject) {
  60512. _super.prototype.serialize.call(this, serializationObject);
  60513. serializationObject.subdivisionsX = this._subdivisionsX;
  60514. serializationObject.subdivisionsY = this._subdivisionsY;
  60515. serializationObject.minX = this._minX;
  60516. serializationObject.maxX = this._maxX;
  60517. serializationObject.minZ = this._minZ;
  60518. serializationObject.maxZ = this._maxZ;
  60519. serializationObject.width = this._width;
  60520. serializationObject.height = this._height;
  60521. };
  60522. GroundMesh.Parse = function (parsedMesh, scene) {
  60523. var result = new GroundMesh(parsedMesh.name, scene);
  60524. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60525. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60526. result._minX = parsedMesh.minX;
  60527. result._maxX = parsedMesh.maxX;
  60528. result._minZ = parsedMesh.minZ;
  60529. result._maxZ = parsedMesh.maxZ;
  60530. result._width = parsedMesh.width;
  60531. result._height = parsedMesh.height;
  60532. return result;
  60533. };
  60534. return GroundMesh;
  60535. }(BABYLON.Mesh));
  60536. BABYLON.GroundMesh = GroundMesh;
  60537. })(BABYLON || (BABYLON = {}));
  60538. //# sourceMappingURL=babylon.groundMesh.js.map
  60539. var BABYLON;
  60540. (function (BABYLON) {
  60541. /**
  60542. * Creates an instance based on a source mesh.
  60543. */
  60544. var InstancedMesh = /** @class */ (function (_super) {
  60545. __extends(InstancedMesh, _super);
  60546. function InstancedMesh(name, source) {
  60547. var _this = _super.call(this, name, source.getScene()) || this;
  60548. source.instances.push(_this);
  60549. _this._sourceMesh = source;
  60550. _this.position.copyFrom(source.position);
  60551. _this.rotation.copyFrom(source.rotation);
  60552. _this.scaling.copyFrom(source.scaling);
  60553. if (source.rotationQuaternion) {
  60554. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60555. }
  60556. _this.infiniteDistance = source.infiniteDistance;
  60557. _this.setPivotMatrix(source.getPivotMatrix());
  60558. _this.refreshBoundingInfo();
  60559. _this._syncSubMeshes();
  60560. return _this;
  60561. }
  60562. /**
  60563. * Returns the string "InstancedMesh".
  60564. */
  60565. InstancedMesh.prototype.getClassName = function () {
  60566. return "InstancedMesh";
  60567. };
  60568. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60569. // Methods
  60570. get: function () {
  60571. return this._sourceMesh.receiveShadows;
  60572. },
  60573. enumerable: true,
  60574. configurable: true
  60575. });
  60576. Object.defineProperty(InstancedMesh.prototype, "material", {
  60577. get: function () {
  60578. return this._sourceMesh.material;
  60579. },
  60580. enumerable: true,
  60581. configurable: true
  60582. });
  60583. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60584. get: function () {
  60585. return this._sourceMesh.visibility;
  60586. },
  60587. enumerable: true,
  60588. configurable: true
  60589. });
  60590. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60591. get: function () {
  60592. return this._sourceMesh.skeleton;
  60593. },
  60594. enumerable: true,
  60595. configurable: true
  60596. });
  60597. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60598. get: function () {
  60599. return this._sourceMesh.renderingGroupId;
  60600. },
  60601. set: function (value) {
  60602. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60603. return;
  60604. }
  60605. //no-op with warning
  60606. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60607. },
  60608. enumerable: true,
  60609. configurable: true
  60610. });
  60611. /**
  60612. * Returns the total number of vertices (integer).
  60613. */
  60614. InstancedMesh.prototype.getTotalVertices = function () {
  60615. return this._sourceMesh.getTotalVertices();
  60616. };
  60617. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60618. get: function () {
  60619. return this._sourceMesh;
  60620. },
  60621. enumerable: true,
  60622. configurable: true
  60623. });
  60624. /**
  60625. * Is this node ready to be used/rendered
  60626. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60627. * @return {boolean} is it ready
  60628. */
  60629. InstancedMesh.prototype.isReady = function (completeCheck) {
  60630. if (completeCheck === void 0) { completeCheck = false; }
  60631. return this._sourceMesh.isReady(completeCheck, true);
  60632. };
  60633. /**
  60634. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60635. */
  60636. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60637. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60638. };
  60639. /**
  60640. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60641. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60642. * The `data` are either a numeric array either a Float32Array.
  60643. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60644. * 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).
  60645. * Note that a new underlying VertexBuffer object is created each call.
  60646. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60647. *
  60648. * Possible `kind` values :
  60649. * - BABYLON.VertexBuffer.PositionKind
  60650. * - BABYLON.VertexBuffer.UVKind
  60651. * - BABYLON.VertexBuffer.UV2Kind
  60652. * - BABYLON.VertexBuffer.UV3Kind
  60653. * - BABYLON.VertexBuffer.UV4Kind
  60654. * - BABYLON.VertexBuffer.UV5Kind
  60655. * - BABYLON.VertexBuffer.UV6Kind
  60656. * - BABYLON.VertexBuffer.ColorKind
  60657. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60658. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60659. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60660. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60661. *
  60662. * Returns the Mesh.
  60663. */
  60664. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60665. if (this.sourceMesh) {
  60666. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60667. }
  60668. return this.sourceMesh;
  60669. };
  60670. /**
  60671. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60672. * If the mesh has no geometry, it is simply returned as it is.
  60673. * The `data` are either a numeric array either a Float32Array.
  60674. * No new underlying VertexBuffer object is created.
  60675. * 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.
  60676. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60677. *
  60678. * Possible `kind` values :
  60679. * - BABYLON.VertexBuffer.PositionKind
  60680. * - BABYLON.VertexBuffer.UVKind
  60681. * - BABYLON.VertexBuffer.UV2Kind
  60682. * - BABYLON.VertexBuffer.UV3Kind
  60683. * - BABYLON.VertexBuffer.UV4Kind
  60684. * - BABYLON.VertexBuffer.UV5Kind
  60685. * - BABYLON.VertexBuffer.UV6Kind
  60686. * - BABYLON.VertexBuffer.ColorKind
  60687. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60688. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60689. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60690. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60691. *
  60692. * Returns the Mesh.
  60693. */
  60694. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60695. if (this.sourceMesh) {
  60696. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60697. }
  60698. return this.sourceMesh;
  60699. };
  60700. /**
  60701. * Sets the mesh indices.
  60702. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60703. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60704. * This method creates a new index buffer each call.
  60705. * Returns the Mesh.
  60706. */
  60707. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60708. if (totalVertices === void 0) { totalVertices = null; }
  60709. if (this.sourceMesh) {
  60710. this.sourceMesh.setIndices(indices, totalVertices);
  60711. }
  60712. return this.sourceMesh;
  60713. };
  60714. /**
  60715. * Boolean : True if the mesh owns the requested kind of data.
  60716. */
  60717. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60718. return this._sourceMesh.isVerticesDataPresent(kind);
  60719. };
  60720. /**
  60721. * Returns an array of indices (IndicesArray).
  60722. */
  60723. InstancedMesh.prototype.getIndices = function () {
  60724. return this._sourceMesh.getIndices();
  60725. };
  60726. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60727. get: function () {
  60728. return this._sourceMesh._positions;
  60729. },
  60730. enumerable: true,
  60731. configurable: true
  60732. });
  60733. /**
  60734. * Sets a new updated BoundingInfo to the mesh.
  60735. * Returns the mesh.
  60736. */
  60737. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60738. var meshBB = this._sourceMesh.getBoundingInfo();
  60739. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60740. this._updateBoundingInfo();
  60741. return this;
  60742. };
  60743. InstancedMesh.prototype._preActivate = function () {
  60744. if (this._currentLOD) {
  60745. this._currentLOD._preActivate();
  60746. }
  60747. return this;
  60748. };
  60749. InstancedMesh.prototype._activate = function (renderId) {
  60750. if (this._currentLOD) {
  60751. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60752. }
  60753. return this;
  60754. };
  60755. /**
  60756. * Returns the current associated LOD AbstractMesh.
  60757. */
  60758. InstancedMesh.prototype.getLOD = function (camera) {
  60759. if (!camera) {
  60760. return this;
  60761. }
  60762. var boundingInfo = this.getBoundingInfo();
  60763. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60764. if (this._currentLOD === this.sourceMesh) {
  60765. return this;
  60766. }
  60767. return this._currentLOD;
  60768. };
  60769. InstancedMesh.prototype._syncSubMeshes = function () {
  60770. this.releaseSubMeshes();
  60771. if (this._sourceMesh.subMeshes) {
  60772. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60773. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60774. }
  60775. }
  60776. return this;
  60777. };
  60778. InstancedMesh.prototype._generatePointsArray = function () {
  60779. return this._sourceMesh._generatePointsArray();
  60780. };
  60781. /**
  60782. * Creates a new InstancedMesh from the current mesh.
  60783. * - name (string) : the cloned mesh name
  60784. * - newParent (optional Node) : the optional Node to parent the clone to.
  60785. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60786. *
  60787. * Returns the clone.
  60788. */
  60789. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60790. var result = this._sourceMesh.createInstance(name);
  60791. // Deep copy
  60792. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60793. // Bounding info
  60794. this.refreshBoundingInfo();
  60795. // Parent
  60796. if (newParent) {
  60797. result.parent = newParent;
  60798. }
  60799. if (!doNotCloneChildren) {
  60800. // Children
  60801. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60802. var mesh = this.getScene().meshes[index];
  60803. if (mesh.parent === this) {
  60804. mesh.clone(mesh.name, result);
  60805. }
  60806. }
  60807. }
  60808. result.computeWorldMatrix(true);
  60809. return result;
  60810. };
  60811. /**
  60812. * Disposes the InstancedMesh.
  60813. * Returns nothing.
  60814. */
  60815. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60816. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60817. // Remove from mesh
  60818. var index = this._sourceMesh.instances.indexOf(this);
  60819. this._sourceMesh.instances.splice(index, 1);
  60820. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60821. };
  60822. return InstancedMesh;
  60823. }(BABYLON.AbstractMesh));
  60824. BABYLON.InstancedMesh = InstancedMesh;
  60825. })(BABYLON || (BABYLON = {}));
  60826. //# sourceMappingURL=babylon.instancedMesh.js.map
  60827. var BABYLON;
  60828. (function (BABYLON) {
  60829. var LinesMesh = /** @class */ (function (_super) {
  60830. __extends(LinesMesh, _super);
  60831. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60832. if (scene === void 0) { scene = null; }
  60833. if (parent === void 0) { parent = null; }
  60834. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60835. _this.useVertexColor = useVertexColor;
  60836. _this.useVertexAlpha = useVertexAlpha;
  60837. _this.color = new BABYLON.Color3(1, 1, 1);
  60838. _this.alpha = 1;
  60839. if (source) {
  60840. _this.color = source.color.clone();
  60841. _this.alpha = source.alpha;
  60842. _this.useVertexColor = source.useVertexColor;
  60843. _this.useVertexAlpha = source.useVertexAlpha;
  60844. }
  60845. _this._intersectionThreshold = 0.1;
  60846. var defines = [];
  60847. var options = {
  60848. attributes: [BABYLON.VertexBuffer.PositionKind],
  60849. uniforms: ["world", "viewProjection"],
  60850. needAlphaBlending: true,
  60851. defines: defines
  60852. };
  60853. if (useVertexAlpha === false) {
  60854. options.needAlphaBlending = false;
  60855. }
  60856. if (!useVertexColor) {
  60857. options.uniforms.push("color");
  60858. }
  60859. else {
  60860. options.defines.push("#define VERTEXCOLOR");
  60861. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60862. }
  60863. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60864. return _this;
  60865. }
  60866. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60867. /**
  60868. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60869. * This margin is expressed in world space coordinates, so its value may vary.
  60870. * Default value is 0.1
  60871. * @returns the intersection Threshold value.
  60872. */
  60873. get: function () {
  60874. return this._intersectionThreshold;
  60875. },
  60876. /**
  60877. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60878. * This margin is expressed in world space coordinates, so its value may vary.
  60879. * @param value the new threshold to apply
  60880. */
  60881. set: function (value) {
  60882. if (this._intersectionThreshold === value) {
  60883. return;
  60884. }
  60885. this._intersectionThreshold = value;
  60886. if (this.geometry) {
  60887. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60888. }
  60889. },
  60890. enumerable: true,
  60891. configurable: true
  60892. });
  60893. /**
  60894. * Returns the string "LineMesh"
  60895. */
  60896. LinesMesh.prototype.getClassName = function () {
  60897. return "LinesMesh";
  60898. };
  60899. Object.defineProperty(LinesMesh.prototype, "material", {
  60900. get: function () {
  60901. return this._colorShader;
  60902. },
  60903. set: function (value) {
  60904. // Do nothing
  60905. },
  60906. enumerable: true,
  60907. configurable: true
  60908. });
  60909. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60910. get: function () {
  60911. return false;
  60912. },
  60913. enumerable: true,
  60914. configurable: true
  60915. });
  60916. LinesMesh.prototype.createInstance = function (name) {
  60917. throw new Error("LinesMeshes do not support createInstance.");
  60918. };
  60919. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60920. if (!this._geometry) {
  60921. return this;
  60922. }
  60923. // VBOs
  60924. this._geometry._bind(this._colorShader.getEffect());
  60925. // Color
  60926. if (!this.useVertexColor) {
  60927. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60928. }
  60929. return this;
  60930. };
  60931. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60932. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60933. return this;
  60934. }
  60935. var engine = this.getScene().getEngine();
  60936. // Draw order
  60937. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60938. return this;
  60939. };
  60940. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60941. this._colorShader.dispose();
  60942. _super.prototype.dispose.call(this, doNotRecurse);
  60943. };
  60944. /**
  60945. * Returns a new LineMesh object cloned from the current one.
  60946. */
  60947. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60948. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60949. };
  60950. return LinesMesh;
  60951. }(BABYLON.Mesh));
  60952. BABYLON.LinesMesh = LinesMesh;
  60953. })(BABYLON || (BABYLON = {}));
  60954. //# sourceMappingURL=babylon.linesMesh.js.map
  60955. var BABYLON;
  60956. (function (BABYLON) {
  60957. /**
  60958. * Class containing static functions to help procedurally build meshes
  60959. */
  60960. var MeshBuilder = /** @class */ (function () {
  60961. function MeshBuilder() {
  60962. }
  60963. MeshBuilder.updateSideOrientation = function (orientation) {
  60964. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60965. return BABYLON.Mesh.DOUBLESIDE;
  60966. }
  60967. if (orientation === undefined || orientation === null) {
  60968. return BABYLON.Mesh.FRONTSIDE;
  60969. }
  60970. return orientation;
  60971. };
  60972. /**
  60973. * Creates a box mesh
  60974. * * The parameter `size` sets the size (float) of each box side (default 1)
  60975. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60976. * * 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)
  60977. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60978. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60979. * * 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
  60980. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60981. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60982. * @param name defines the name of the mesh
  60983. * @param options defines the options used to create the mesh
  60984. * @param scene defines the hosting scene
  60985. * @returns the box mesh
  60986. */
  60987. MeshBuilder.CreateBox = function (name, options, scene) {
  60988. if (scene === void 0) { scene = null; }
  60989. var box = new BABYLON.Mesh(name, scene);
  60990. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60991. box._originalBuilderSideOrientation = options.sideOrientation;
  60992. var vertexData = BABYLON.VertexData.CreateBox(options);
  60993. vertexData.applyToMesh(box, options.updatable);
  60994. return box;
  60995. };
  60996. /**
  60997. * Creates a sphere mesh
  60998. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60999. * * 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`)
  61000. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61001. * * 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
  61002. * * 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)
  61003. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61004. * * 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
  61005. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61006. * @param name defines the name of the mesh
  61007. * @param options defines the options used to create the mesh
  61008. * @param scene defines the hosting scene
  61009. * @returns the sphere mesh
  61010. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61011. */
  61012. MeshBuilder.CreateSphere = function (name, options, scene) {
  61013. var sphere = new BABYLON.Mesh(name, scene);
  61014. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61015. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61016. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61017. vertexData.applyToMesh(sphere, options.updatable);
  61018. return sphere;
  61019. };
  61020. /**
  61021. * Creates a plane polygonal mesh. By default, this is a disc
  61022. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61023. * * 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
  61024. * * 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
  61025. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61026. * * 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
  61027. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61028. * @param name defines the name of the mesh
  61029. * @param options defines the options used to create the mesh
  61030. * @param scene defines the hosting scene
  61031. * @returns the plane polygonal mesh
  61032. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61033. */
  61034. MeshBuilder.CreateDisc = function (name, options, scene) {
  61035. if (scene === void 0) { scene = null; }
  61036. var disc = new BABYLON.Mesh(name, scene);
  61037. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61038. disc._originalBuilderSideOrientation = options.sideOrientation;
  61039. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61040. vertexData.applyToMesh(disc, options.updatable);
  61041. return disc;
  61042. };
  61043. /**
  61044. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61045. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61046. * * 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`)
  61047. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61048. * * 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
  61049. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61050. * * 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
  61051. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61052. * @param name defines the name of the mesh
  61053. * @param options defines the options used to create the mesh
  61054. * @param scene defines the hosting scene
  61055. * @returns the icosahedron mesh
  61056. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61057. */
  61058. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61059. var sphere = new BABYLON.Mesh(name, scene);
  61060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61061. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61062. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61063. vertexData.applyToMesh(sphere, options.updatable);
  61064. return sphere;
  61065. };
  61066. ;
  61067. /**
  61068. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61069. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61070. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61071. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61072. * * 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
  61073. * * 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
  61074. * * 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
  61075. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61076. * * 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
  61077. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61078. * * 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
  61079. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61080. * * 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
  61081. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61082. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61083. * @param name defines the name of the mesh
  61084. * @param options defines the options used to create the mesh
  61085. * @param scene defines the hosting scene
  61086. * @returns the ribbon mesh
  61087. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61088. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61089. */
  61090. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61091. if (scene === void 0) { scene = null; }
  61092. var pathArray = options.pathArray;
  61093. var closeArray = options.closeArray;
  61094. var closePath = options.closePath;
  61095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61096. var instance = options.instance;
  61097. var updatable = options.updatable;
  61098. if (instance) { // existing ribbon instance update
  61099. // positionFunction : ribbon case
  61100. // only pathArray and sideOrientation parameters are taken into account for positions update
  61101. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61102. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61103. var positionFunction = function (positions) {
  61104. var minlg = pathArray[0].length;
  61105. var i = 0;
  61106. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61107. for (var si = 1; si <= ns; si++) {
  61108. for (var p = 0; p < pathArray.length; p++) {
  61109. var path = pathArray[p];
  61110. var l = path.length;
  61111. minlg = (minlg < l) ? minlg : l;
  61112. var j = 0;
  61113. while (j < minlg) {
  61114. positions[i] = path[j].x;
  61115. positions[i + 1] = path[j].y;
  61116. positions[i + 2] = path[j].z;
  61117. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61118. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61119. }
  61120. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61121. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61122. }
  61123. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61124. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61125. }
  61126. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61127. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61128. }
  61129. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61130. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61131. }
  61132. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61133. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61134. }
  61135. j++;
  61136. i += 3;
  61137. }
  61138. if (instance._closePath) {
  61139. positions[i] = path[0].x;
  61140. positions[i + 1] = path[0].y;
  61141. positions[i + 2] = path[0].z;
  61142. i += 3;
  61143. }
  61144. }
  61145. }
  61146. };
  61147. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61148. positionFunction(positions);
  61149. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61150. instance._boundingInfo.update(instance._worldMatrix);
  61151. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61152. if (options.colors) {
  61153. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61154. for (var c = 0; c < options.colors.length; c++) {
  61155. colors[c * 4] = options.colors[c].r;
  61156. colors[c * 4 + 1] = options.colors[c].g;
  61157. colors[c * 4 + 2] = options.colors[c].b;
  61158. colors[c * 4 + 3] = options.colors[c].a;
  61159. }
  61160. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61161. }
  61162. if (options.uvs) {
  61163. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61164. for (var i = 0; i < options.uvs.length; i++) {
  61165. uvs[i * 2] = options.uvs[i].x;
  61166. uvs[i * 2 + 1] = options.uvs[i].y;
  61167. }
  61168. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61169. }
  61170. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61171. var indices = instance.getIndices();
  61172. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61173. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61174. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61175. if (instance._closePath) {
  61176. var indexFirst = 0;
  61177. var indexLast = 0;
  61178. for (var p = 0; p < pathArray.length; p++) {
  61179. indexFirst = instance._idx[p] * 3;
  61180. if (p + 1 < pathArray.length) {
  61181. indexLast = (instance._idx[p + 1] - 1) * 3;
  61182. }
  61183. else {
  61184. indexLast = normals.length - 3;
  61185. }
  61186. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61187. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61188. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61189. normals[indexLast] = normals[indexFirst];
  61190. normals[indexLast + 1] = normals[indexFirst + 1];
  61191. normals[indexLast + 2] = normals[indexFirst + 2];
  61192. }
  61193. }
  61194. if (!(instance.areNormalsFrozen)) {
  61195. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61196. }
  61197. }
  61198. return instance;
  61199. }
  61200. else { // new ribbon creation
  61201. var ribbon = new BABYLON.Mesh(name, scene);
  61202. ribbon._originalBuilderSideOrientation = sideOrientation;
  61203. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61204. if (closePath) {
  61205. ribbon._idx = vertexData._idx;
  61206. }
  61207. ribbon._closePath = closePath;
  61208. ribbon._closeArray = closeArray;
  61209. vertexData.applyToMesh(ribbon, updatable);
  61210. return ribbon;
  61211. }
  61212. };
  61213. /**
  61214. * Creates a cylinder or a cone mesh
  61215. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61216. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61217. * * 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.
  61218. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61219. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61220. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61221. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61222. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61223. * * 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).
  61224. * * 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
  61225. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61226. * * 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
  61227. * * 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.
  61228. * * If `enclose` is false, a ring surface is one element.
  61229. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61230. * * 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
  61231. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61232. * * 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
  61233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61234. * @param name defines the name of the mesh
  61235. * @param options defines the options used to create the mesh
  61236. * @param scene defines the hosting scene
  61237. * @returns the cylinder mesh
  61238. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61239. */
  61240. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61241. var cylinder = new BABYLON.Mesh(name, scene);
  61242. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61243. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61244. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61245. vertexData.applyToMesh(cylinder, options.updatable);
  61246. return cylinder;
  61247. };
  61248. /**
  61249. * Creates a torus mesh
  61250. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61251. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61252. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61253. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61254. * * 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
  61255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61256. * @param name defines the name of the mesh
  61257. * @param options defines the options used to create the mesh
  61258. * @param scene defines the hosting scene
  61259. * @returns the torus mesh
  61260. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61261. */
  61262. MeshBuilder.CreateTorus = function (name, options, scene) {
  61263. var torus = new BABYLON.Mesh(name, scene);
  61264. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61265. torus._originalBuilderSideOrientation = options.sideOrientation;
  61266. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61267. vertexData.applyToMesh(torus, options.updatable);
  61268. return torus;
  61269. };
  61270. /**
  61271. * Creates a torus knot mesh
  61272. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61273. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61274. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61275. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61276. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61277. * * 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
  61278. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61279. * @param name defines the name of the mesh
  61280. * @param options defines the options used to create the mesh
  61281. * @param scene defines the hosting scene
  61282. * @returns the torus knot mesh
  61283. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61284. */
  61285. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61286. var torusKnot = new BABYLON.Mesh(name, scene);
  61287. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61288. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61289. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61290. vertexData.applyToMesh(torusKnot, options.updatable);
  61291. return torusKnot;
  61292. };
  61293. /**
  61294. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61295. * * 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
  61296. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61297. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61298. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61299. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61300. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61301. * * 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
  61302. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61303. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61304. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61305. * @param name defines the name of the new line system
  61306. * @param options defines the options used to create the line system
  61307. * @param scene defines the hosting scene
  61308. * @returns a new line system mesh
  61309. */
  61310. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61311. var instance = options.instance;
  61312. var lines = options.lines;
  61313. var colors = options.colors;
  61314. if (instance) { // lines update
  61315. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61316. var vertexColor;
  61317. var lineColors;
  61318. if (colors) {
  61319. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61320. }
  61321. var i = 0;
  61322. var c = 0;
  61323. for (var l = 0; l < lines.length; l++) {
  61324. var points = lines[l];
  61325. for (var p = 0; p < points.length; p++) {
  61326. positions[i] = points[p].x;
  61327. positions[i + 1] = points[p].y;
  61328. positions[i + 2] = points[p].z;
  61329. if (colors && vertexColor) {
  61330. lineColors = colors[l];
  61331. vertexColor[c] = lineColors[p].r;
  61332. vertexColor[c + 1] = lineColors[p].g;
  61333. vertexColor[c + 2] = lineColors[p].b;
  61334. vertexColor[c + 3] = lineColors[p].a;
  61335. c += 4;
  61336. }
  61337. i += 3;
  61338. }
  61339. }
  61340. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61341. if (colors && vertexColor) {
  61342. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61343. }
  61344. return instance;
  61345. }
  61346. // line system creation
  61347. var useVertexColor = (colors) ? true : false;
  61348. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61349. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61350. vertexData.applyToMesh(lineSystem, options.updatable);
  61351. return lineSystem;
  61352. };
  61353. /**
  61354. * Creates a line mesh
  61355. * 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
  61356. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61357. * * The parameter `points` is an array successive Vector3
  61358. * * 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
  61359. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61360. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61361. * * When updating an instance, remember that only point positions can change, not the number of points
  61362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61363. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61364. * @param name defines the name of the new line system
  61365. * @param options defines the options used to create the line system
  61366. * @param scene defines the hosting scene
  61367. * @returns a new line mesh
  61368. */
  61369. MeshBuilder.CreateLines = function (name, options, scene) {
  61370. if (scene === void 0) { scene = null; }
  61371. var colors = (options.colors) ? [options.colors] : null;
  61372. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61373. return lines;
  61374. };
  61375. /**
  61376. * Creates a dashed line mesh
  61377. * * 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
  61378. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61379. * * The parameter `points` is an array successive Vector3
  61380. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61381. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61382. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61383. * * 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
  61384. * * When updating an instance, remember that only point positions can change, not the number of points
  61385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61386. * @param name defines the name of the mesh
  61387. * @param options defines the options used to create the mesh
  61388. * @param scene defines the hosting scene
  61389. * @returns the dashed line mesh
  61390. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61391. */
  61392. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61393. if (scene === void 0) { scene = null; }
  61394. var points = options.points;
  61395. var instance = options.instance;
  61396. var gapSize = options.gapSize || 1;
  61397. var dashSize = options.dashSize || 3;
  61398. if (instance) { // dashed lines update
  61399. var positionFunction = function (positions) {
  61400. var curvect = BABYLON.Vector3.Zero();
  61401. var nbSeg = positions.length / 6;
  61402. var lg = 0;
  61403. var nb = 0;
  61404. var shft = 0;
  61405. var dashshft = 0;
  61406. var curshft = 0;
  61407. var p = 0;
  61408. var i = 0;
  61409. var j = 0;
  61410. for (i = 0; i < points.length - 1; i++) {
  61411. points[i + 1].subtractToRef(points[i], curvect);
  61412. lg += curvect.length();
  61413. }
  61414. shft = lg / nbSeg;
  61415. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61416. for (i = 0; i < points.length - 1; i++) {
  61417. points[i + 1].subtractToRef(points[i], curvect);
  61418. nb = Math.floor(curvect.length() / shft);
  61419. curvect.normalize();
  61420. j = 0;
  61421. while (j < nb && p < positions.length) {
  61422. curshft = shft * j;
  61423. positions[p] = points[i].x + curshft * curvect.x;
  61424. positions[p + 1] = points[i].y + curshft * curvect.y;
  61425. positions[p + 2] = points[i].z + curshft * curvect.z;
  61426. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61427. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61428. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61429. p += 6;
  61430. j++;
  61431. }
  61432. }
  61433. while (p < positions.length) {
  61434. positions[p] = points[i].x;
  61435. positions[p + 1] = points[i].y;
  61436. positions[p + 2] = points[i].z;
  61437. p += 3;
  61438. }
  61439. };
  61440. instance.updateMeshPositions(positionFunction, false);
  61441. return instance;
  61442. }
  61443. // dashed lines creation
  61444. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61445. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61446. vertexData.applyToMesh(dashedLines, options.updatable);
  61447. dashedLines.dashSize = dashSize;
  61448. dashedLines.gapSize = gapSize;
  61449. return dashedLines;
  61450. };
  61451. /**
  61452. * 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.
  61453. * * 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.
  61454. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61455. * * 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.
  61456. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61457. * * 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
  61458. * * 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
  61459. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61460. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61461. * * 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
  61462. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61463. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61464. * @param name defines the name of the mesh
  61465. * @param options defines the options used to create the mesh
  61466. * @param scene defines the hosting scene
  61467. * @returns the extruded shape mesh
  61468. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61469. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61470. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61471. */
  61472. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61473. if (scene === void 0) { scene = null; }
  61474. var path = options.path;
  61475. var shape = options.shape;
  61476. var scale = options.scale || 1;
  61477. var rotation = options.rotation || 0;
  61478. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61479. var updatable = options.updatable;
  61480. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61481. var instance = options.instance || null;
  61482. var invertUV = options.invertUV || false;
  61483. 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);
  61484. };
  61485. /**
  61486. * Creates an custom extruded shape mesh.
  61487. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61488. * * 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.
  61489. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61490. * * 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
  61491. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61492. * * 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
  61493. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61494. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61495. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61496. * * 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
  61497. * * 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
  61498. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61499. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61500. * * 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
  61501. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61502. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61503. * @param name defines the name of the mesh
  61504. * @param options defines the options used to create the mesh
  61505. * @param scene defines the hosting scene
  61506. * @returns the custom extruded shape mesh
  61507. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61508. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61509. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61510. */
  61511. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61512. var path = options.path;
  61513. var shape = options.shape;
  61514. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61515. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61516. var ribbonCloseArray = options.ribbonCloseArray || false;
  61517. var ribbonClosePath = options.ribbonClosePath || false;
  61518. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61519. var updatable = options.updatable;
  61520. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61521. var instance = options.instance;
  61522. var invertUV = options.invertUV || false;
  61523. 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);
  61524. };
  61525. /**
  61526. * Creates lathe mesh.
  61527. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61528. * * 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
  61529. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61530. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61531. * * 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
  61532. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61533. * * 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
  61534. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61535. * * 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
  61536. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61537. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61538. * @param name defines the name of the mesh
  61539. * @param options defines the options used to create the mesh
  61540. * @param scene defines the hosting scene
  61541. * @returns the lathe mesh
  61542. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61543. */
  61544. MeshBuilder.CreateLathe = function (name, options, scene) {
  61545. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61546. var closed = (options.closed === undefined) ? true : options.closed;
  61547. var shape = options.shape;
  61548. var radius = options.radius || 1;
  61549. var tessellation = options.tessellation || 64;
  61550. var updatable = options.updatable;
  61551. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61552. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61553. var pi2 = Math.PI * 2;
  61554. var paths = new Array();
  61555. var invertUV = options.invertUV || false;
  61556. var i = 0;
  61557. var p = 0;
  61558. var step = pi2 / tessellation * arc;
  61559. var rotated;
  61560. var path = new Array();
  61561. for (i = 0; i <= tessellation; i++) {
  61562. var path = [];
  61563. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61564. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61565. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61566. }
  61567. for (p = 0; p < shape.length; p++) {
  61568. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61569. path.push(rotated);
  61570. }
  61571. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61572. 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));
  61573. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61574. }
  61575. paths.push(path);
  61576. }
  61577. // lathe ribbon
  61578. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61579. return lathe;
  61580. };
  61581. /**
  61582. * Creates a plane mesh
  61583. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61584. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61585. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61586. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61587. * * 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
  61588. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61589. * @param name defines the name of the mesh
  61590. * @param options defines the options used to create the mesh
  61591. * @param scene defines the hosting scene
  61592. * @returns the plane mesh
  61593. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61594. */
  61595. MeshBuilder.CreatePlane = function (name, options, scene) {
  61596. var plane = new BABYLON.Mesh(name, scene);
  61597. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61598. plane._originalBuilderSideOrientation = options.sideOrientation;
  61599. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61600. vertexData.applyToMesh(plane, options.updatable);
  61601. if (options.sourcePlane) {
  61602. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61603. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61604. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61605. plane.rotate(vectorProduct, product);
  61606. }
  61607. return plane;
  61608. };
  61609. /**
  61610. * Creates a ground mesh
  61611. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61612. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61613. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61614. * @param name defines the name of the mesh
  61615. * @param options defines the options used to create the mesh
  61616. * @param scene defines the hosting scene
  61617. * @returns the ground mesh
  61618. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61619. */
  61620. MeshBuilder.CreateGround = function (name, options, scene) {
  61621. var ground = new BABYLON.GroundMesh(name, scene);
  61622. ground._setReady(false);
  61623. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61624. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61625. ground._width = options.width || 1;
  61626. ground._height = options.height || 1;
  61627. ground._maxX = ground._width / 2;
  61628. ground._maxZ = ground._height / 2;
  61629. ground._minX = -ground._maxX;
  61630. ground._minZ = -ground._maxZ;
  61631. var vertexData = BABYLON.VertexData.CreateGround(options);
  61632. vertexData.applyToMesh(ground, options.updatable);
  61633. ground._setReady(true);
  61634. return ground;
  61635. };
  61636. /**
  61637. * Creates a tiled ground mesh
  61638. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61639. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61640. * * 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
  61641. * * 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
  61642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61643. * @param name defines the name of the mesh
  61644. * @param options defines the options used to create the mesh
  61645. * @param scene defines the hosting scene
  61646. * @returns the tiled ground mesh
  61647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61648. */
  61649. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61650. var tiledGround = new BABYLON.Mesh(name, scene);
  61651. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61652. vertexData.applyToMesh(tiledGround, options.updatable);
  61653. return tiledGround;
  61654. };
  61655. /**
  61656. * Creates a ground mesh from a height map
  61657. * * The parameter `url` sets the URL of the height map image resource.
  61658. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61659. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61660. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61661. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61662. * * 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.
  61663. * * 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).
  61664. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61665. * @param name defines the name of the mesh
  61666. * @param url defines the url to the height map
  61667. * @param options defines the options used to create the mesh
  61668. * @param scene defines the hosting scene
  61669. * @returns the ground mesh
  61670. * @see http://doc.babylonjs.com/babylon101/height_map
  61671. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61672. */
  61673. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61674. var width = options.width || 10.0;
  61675. var height = options.height || 10.0;
  61676. var subdivisions = options.subdivisions || 1 | 0;
  61677. var minHeight = options.minHeight || 0.0;
  61678. var maxHeight = options.maxHeight || 1.0;
  61679. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61680. var updatable = options.updatable;
  61681. var onReady = options.onReady;
  61682. var ground = new BABYLON.GroundMesh(name, scene);
  61683. ground._subdivisionsX = subdivisions;
  61684. ground._subdivisionsY = subdivisions;
  61685. ground._width = width;
  61686. ground._height = height;
  61687. ground._maxX = ground._width / 2.0;
  61688. ground._maxZ = ground._height / 2.0;
  61689. ground._minX = -ground._maxX;
  61690. ground._minZ = -ground._maxZ;
  61691. ground._setReady(false);
  61692. var onload = function (img) {
  61693. // Getting height map data
  61694. var canvas = document.createElement("canvas");
  61695. var context = canvas.getContext("2d");
  61696. if (!context) {
  61697. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61698. }
  61699. if (scene.isDisposed) {
  61700. return;
  61701. }
  61702. var bufferWidth = img.width;
  61703. var bufferHeight = img.height;
  61704. canvas.width = bufferWidth;
  61705. canvas.height = bufferHeight;
  61706. context.drawImage(img, 0, 0);
  61707. // Create VertexData from map data
  61708. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61709. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61710. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61711. width: width, height: height,
  61712. subdivisions: subdivisions,
  61713. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61714. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61715. });
  61716. vertexData.applyToMesh(ground, updatable);
  61717. //execute ready callback, if set
  61718. if (onReady) {
  61719. onReady(ground);
  61720. }
  61721. ground._setReady(true);
  61722. };
  61723. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61724. return ground;
  61725. };
  61726. /**
  61727. * Creates a polygon mesh
  61728. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61729. * * 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
  61730. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61731. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61732. * * 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)
  61733. * * Remember you can only change the shape positions, not their number when updating a polygon
  61734. * @param name defines the name of the mesh
  61735. * @param options defines the options used to create the mesh
  61736. * @param scene defines the hosting scene
  61737. * @returns the polygon mesh
  61738. */
  61739. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61740. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61741. var shape = options.shape;
  61742. var holes = options.holes || [];
  61743. var depth = options.depth || 0;
  61744. var contours = [];
  61745. var hole = [];
  61746. for (var i = 0; i < shape.length; i++) {
  61747. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61748. }
  61749. var epsilon = 0.00000001;
  61750. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61751. contours.pop();
  61752. }
  61753. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61754. for (var hNb = 0; hNb < holes.length; hNb++) {
  61755. hole = [];
  61756. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61757. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61758. }
  61759. polygonTriangulation.addHole(hole);
  61760. }
  61761. var polygon = polygonTriangulation.build(options.updatable, depth);
  61762. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61763. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61764. vertexData.applyToMesh(polygon, options.updatable);
  61765. return polygon;
  61766. };
  61767. ;
  61768. /**
  61769. * Creates an extruded polygon mesh, with depth in the Y direction.
  61770. * * 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)
  61771. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61772. * @param name defines the name of the mesh
  61773. * @param options defines the options used to create the mesh
  61774. * @param scene defines the hosting scene
  61775. * @returns the polygon mesh
  61776. */
  61777. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61778. return MeshBuilder.CreatePolygon(name, options, scene);
  61779. };
  61780. ;
  61781. /**
  61782. * Creates a tube mesh.
  61783. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61784. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61785. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61786. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61787. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61788. * * 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)
  61789. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61790. * * 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
  61791. * * 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
  61792. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61793. * * 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
  61794. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61795. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61796. * @param name defines the name of the mesh
  61797. * @param options defines the options used to create the mesh
  61798. * @param scene defines the hosting scene
  61799. * @returns the tube mesh
  61800. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61801. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61802. */
  61803. MeshBuilder.CreateTube = function (name, options, scene) {
  61804. var path = options.path;
  61805. var instance = options.instance;
  61806. var radius = 1.0;
  61807. if (instance) {
  61808. radius = instance.radius;
  61809. }
  61810. if (options.radius !== undefined) {
  61811. radius = options.radius;
  61812. }
  61813. ;
  61814. var tessellation = options.tessellation || 64 | 0;
  61815. var radiusFunction = options.radiusFunction || null;
  61816. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61817. var invertUV = options.invertUV || false;
  61818. var updatable = options.updatable;
  61819. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61820. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61821. // tube geometry
  61822. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61823. var tangents = path3D.getTangents();
  61824. var normals = path3D.getNormals();
  61825. var distances = path3D.getDistances();
  61826. var pi2 = Math.PI * 2;
  61827. var step = pi2 / tessellation * arc;
  61828. var returnRadius = function () { return radius; };
  61829. var radiusFunctionFinal = radiusFunction || returnRadius;
  61830. var circlePath;
  61831. var rad;
  61832. var normal;
  61833. var rotated;
  61834. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61835. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61836. for (var i = 0; i < path.length; i++) {
  61837. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61838. circlePath = Array(); // current circle array
  61839. normal = normals[i]; // current normal
  61840. for (var t = 0; t < tessellation; t++) {
  61841. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61842. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61843. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61844. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61845. circlePath[t] = rotated;
  61846. }
  61847. circlePaths[index] = circlePath;
  61848. index++;
  61849. }
  61850. // cap
  61851. var capPath = function (nbPoints, pathIndex) {
  61852. var pointCap = Array();
  61853. for (var i = 0; i < nbPoints; i++) {
  61854. pointCap.push(path[pathIndex]);
  61855. }
  61856. return pointCap;
  61857. };
  61858. switch (cap) {
  61859. case BABYLON.Mesh.NO_CAP:
  61860. break;
  61861. case BABYLON.Mesh.CAP_START:
  61862. circlePaths[0] = capPath(tessellation, 0);
  61863. circlePaths[1] = circlePaths[2].slice(0);
  61864. break;
  61865. case BABYLON.Mesh.CAP_END:
  61866. circlePaths[index] = circlePaths[index - 1].slice(0);
  61867. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61868. break;
  61869. case BABYLON.Mesh.CAP_ALL:
  61870. circlePaths[0] = capPath(tessellation, 0);
  61871. circlePaths[1] = circlePaths[2].slice(0);
  61872. circlePaths[index] = circlePaths[index - 1].slice(0);
  61873. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61874. break;
  61875. default:
  61876. break;
  61877. }
  61878. return circlePaths;
  61879. };
  61880. var path3D;
  61881. var pathArray;
  61882. if (instance) { // tube update
  61883. var arc = options.arc || instance.arc;
  61884. path3D = (instance.path3D).update(path);
  61885. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61886. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61887. instance.path3D = path3D;
  61888. instance.pathArray = pathArray;
  61889. instance.arc = arc;
  61890. instance.radius = radius;
  61891. return instance;
  61892. }
  61893. // tube creation
  61894. path3D = new BABYLON.Path3D(path);
  61895. var newPathArray = new Array();
  61896. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61897. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61898. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61899. tube.pathArray = pathArray;
  61900. tube.path3D = path3D;
  61901. tube.tessellation = tessellation;
  61902. tube.cap = cap;
  61903. tube.arc = options.arc;
  61904. tube.radius = radius;
  61905. return tube;
  61906. };
  61907. /**
  61908. * Creates a polyhedron mesh
  61909. * * 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
  61910. * * The parameter `size` (positive float, default 1) sets the polygon size
  61911. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61912. * * 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`
  61913. * * 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
  61914. * * 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)`)
  61915. * * 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
  61916. * * 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
  61917. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61918. * * 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
  61919. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61920. * @param name defines the name of the mesh
  61921. * @param options defines the options used to create the mesh
  61922. * @param scene defines the hosting scene
  61923. * @returns the polyhedron mesh
  61924. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61925. */
  61926. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61927. var polyhedron = new BABYLON.Mesh(name, scene);
  61928. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61929. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61930. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61931. vertexData.applyToMesh(polyhedron, options.updatable);
  61932. return polyhedron;
  61933. };
  61934. /**
  61935. * Creates a decal mesh.
  61936. * 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
  61937. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61938. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61939. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61940. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61941. * @param name defines the name of the mesh
  61942. * @param sourceMesh defines the mesh where the decal must be applied
  61943. * @param options defines the options used to create the mesh
  61944. * @param scene defines the hosting scene
  61945. * @returns the decal mesh
  61946. * @see http://doc.babylonjs.com/how_to/decals
  61947. */
  61948. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61949. var indices = sourceMesh.getIndices();
  61950. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61951. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61952. var position = options.position || BABYLON.Vector3.Zero();
  61953. var normal = options.normal || BABYLON.Vector3.Up();
  61954. var size = options.size || BABYLON.Vector3.One();
  61955. var angle = options.angle || 0;
  61956. // Getting correct rotation
  61957. if (!normal) {
  61958. var target = new BABYLON.Vector3(0, 0, 1);
  61959. var camera = sourceMesh.getScene().activeCamera;
  61960. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61961. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61962. }
  61963. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61964. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61965. var pitch = Math.atan2(normal.y, len);
  61966. // Matrix
  61967. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61968. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61969. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61970. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61971. var vertexData = new BABYLON.VertexData();
  61972. vertexData.indices = [];
  61973. vertexData.positions = [];
  61974. vertexData.normals = [];
  61975. vertexData.uvs = [];
  61976. var currentVertexDataIndex = 0;
  61977. var extractDecalVector3 = function (indexId) {
  61978. var result = new BABYLON.PositionNormalVertex();
  61979. if (!indices || !positions || !normals) {
  61980. return result;
  61981. }
  61982. var vertexId = indices[indexId];
  61983. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61984. // Send vector to decal local world
  61985. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61986. // Get normal
  61987. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61988. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61989. return result;
  61990. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61991. var clip = function (vertices, axis) {
  61992. if (vertices.length === 0) {
  61993. return vertices;
  61994. }
  61995. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61996. var clipVertices = function (v0, v1) {
  61997. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61998. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61999. };
  62000. var result = new Array();
  62001. for (var index = 0; index < vertices.length; index += 3) {
  62002. var v1Out;
  62003. var v2Out;
  62004. var v3Out;
  62005. var total = 0;
  62006. var nV1 = null;
  62007. var nV2 = null;
  62008. var nV3 = null;
  62009. var nV4 = null;
  62010. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62011. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62012. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62013. v1Out = d1 > 0;
  62014. v2Out = d2 > 0;
  62015. v3Out = d3 > 0;
  62016. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62017. switch (total) {
  62018. case 0:
  62019. result.push(vertices[index]);
  62020. result.push(vertices[index + 1]);
  62021. result.push(vertices[index + 2]);
  62022. break;
  62023. case 1:
  62024. if (v1Out) {
  62025. nV1 = vertices[index + 1];
  62026. nV2 = vertices[index + 2];
  62027. nV3 = clipVertices(vertices[index], nV1);
  62028. nV4 = clipVertices(vertices[index], nV2);
  62029. }
  62030. if (v2Out) {
  62031. nV1 = vertices[index];
  62032. nV2 = vertices[index + 2];
  62033. nV3 = clipVertices(vertices[index + 1], nV1);
  62034. nV4 = clipVertices(vertices[index + 1], nV2);
  62035. result.push(nV3);
  62036. result.push(nV2.clone());
  62037. result.push(nV1.clone());
  62038. result.push(nV2.clone());
  62039. result.push(nV3.clone());
  62040. result.push(nV4);
  62041. break;
  62042. }
  62043. if (v3Out) {
  62044. nV1 = vertices[index];
  62045. nV2 = vertices[index + 1];
  62046. nV3 = clipVertices(vertices[index + 2], nV1);
  62047. nV4 = clipVertices(vertices[index + 2], nV2);
  62048. }
  62049. if (nV1 && nV2 && nV3 && nV4) {
  62050. result.push(nV1.clone());
  62051. result.push(nV2.clone());
  62052. result.push(nV3);
  62053. result.push(nV4);
  62054. result.push(nV3.clone());
  62055. result.push(nV2.clone());
  62056. }
  62057. break;
  62058. case 2:
  62059. if (!v1Out) {
  62060. nV1 = vertices[index].clone();
  62061. nV2 = clipVertices(nV1, vertices[index + 1]);
  62062. nV3 = clipVertices(nV1, vertices[index + 2]);
  62063. result.push(nV1);
  62064. result.push(nV2);
  62065. result.push(nV3);
  62066. }
  62067. if (!v2Out) {
  62068. nV1 = vertices[index + 1].clone();
  62069. nV2 = clipVertices(nV1, vertices[index + 2]);
  62070. nV3 = clipVertices(nV1, vertices[index]);
  62071. result.push(nV1);
  62072. result.push(nV2);
  62073. result.push(nV3);
  62074. }
  62075. if (!v3Out) {
  62076. nV1 = vertices[index + 2].clone();
  62077. nV2 = clipVertices(nV1, vertices[index]);
  62078. nV3 = clipVertices(nV1, vertices[index + 1]);
  62079. result.push(nV1);
  62080. result.push(nV2);
  62081. result.push(nV3);
  62082. }
  62083. break;
  62084. case 3:
  62085. break;
  62086. }
  62087. }
  62088. return result;
  62089. };
  62090. for (var index = 0; index < indices.length; index += 3) {
  62091. var faceVertices = new Array();
  62092. faceVertices.push(extractDecalVector3(index));
  62093. faceVertices.push(extractDecalVector3(index + 1));
  62094. faceVertices.push(extractDecalVector3(index + 2));
  62095. // Clip
  62096. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62097. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62098. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62099. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62100. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62101. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62102. if (faceVertices.length === 0) {
  62103. continue;
  62104. }
  62105. // Add UVs and get back to world
  62106. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62107. var vertex = faceVertices[vIndex];
  62108. //TODO check for Int32Array | Uint32Array | Uint16Array
  62109. vertexData.indices.push(currentVertexDataIndex);
  62110. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62111. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62112. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62113. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62114. currentVertexDataIndex++;
  62115. }
  62116. }
  62117. // Return mesh
  62118. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62119. vertexData.applyToMesh(decal);
  62120. decal.position = position.clone();
  62121. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62122. return decal;
  62123. };
  62124. // Privates
  62125. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62126. // extrusion geometry
  62127. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62128. var tangents = path3D.getTangents();
  62129. var normals = path3D.getNormals();
  62130. var binormals = path3D.getBinormals();
  62131. var distances = path3D.getDistances();
  62132. var angle = 0;
  62133. var returnScale = function () { return scale !== null ? scale : 1; };
  62134. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62135. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62136. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62137. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62138. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62139. for (var i = 0; i < curve.length; i++) {
  62140. var shapePath = new Array();
  62141. var angleStep = rotate(i, distances[i]);
  62142. var scaleRatio = scl(i, distances[i]);
  62143. for (var p = 0; p < shape.length; p++) {
  62144. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62145. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62146. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62147. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62148. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62149. shapePath[p] = rotated;
  62150. }
  62151. shapePaths[index] = shapePath;
  62152. angle += angleStep;
  62153. index++;
  62154. }
  62155. // cap
  62156. var capPath = function (shapePath) {
  62157. var pointCap = Array();
  62158. var barycenter = BABYLON.Vector3.Zero();
  62159. var i;
  62160. for (i = 0; i < shapePath.length; i++) {
  62161. barycenter.addInPlace(shapePath[i]);
  62162. }
  62163. barycenter.scaleInPlace(1.0 / shapePath.length);
  62164. for (i = 0; i < shapePath.length; i++) {
  62165. pointCap.push(barycenter);
  62166. }
  62167. return pointCap;
  62168. };
  62169. switch (cap) {
  62170. case BABYLON.Mesh.NO_CAP:
  62171. break;
  62172. case BABYLON.Mesh.CAP_START:
  62173. shapePaths[0] = capPath(shapePaths[2]);
  62174. shapePaths[1] = shapePaths[2];
  62175. break;
  62176. case BABYLON.Mesh.CAP_END:
  62177. shapePaths[index] = shapePaths[index - 1];
  62178. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62179. break;
  62180. case BABYLON.Mesh.CAP_ALL:
  62181. shapePaths[0] = capPath(shapePaths[2]);
  62182. shapePaths[1] = shapePaths[2];
  62183. shapePaths[index] = shapePaths[index - 1];
  62184. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62185. break;
  62186. default:
  62187. break;
  62188. }
  62189. return shapePaths;
  62190. };
  62191. var path3D;
  62192. var pathArray;
  62193. if (instance) { // instance update
  62194. path3D = (instance.path3D).update(curve);
  62195. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62196. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62197. return instance;
  62198. }
  62199. // extruded shape creation
  62200. path3D = new BABYLON.Path3D(curve);
  62201. var newShapePaths = new Array();
  62202. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62203. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62204. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62205. extrudedGeneric.pathArray = pathArray;
  62206. extrudedGeneric.path3D = path3D;
  62207. extrudedGeneric.cap = cap;
  62208. return extrudedGeneric;
  62209. };
  62210. return MeshBuilder;
  62211. }());
  62212. BABYLON.MeshBuilder = MeshBuilder;
  62213. })(BABYLON || (BABYLON = {}));
  62214. //# sourceMappingURL=babylon.meshBuilder.js.map
  62215. var BABYLON;
  62216. (function (BABYLON) {
  62217. /**
  62218. * Draco compression (https://google.github.io/draco/)
  62219. *
  62220. * This class wraps the Draco module.
  62221. *
  62222. * **Encoder**
  62223. *
  62224. * The encoder is not currently implemented.
  62225. *
  62226. * **Decoder**
  62227. *
  62228. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62229. *
  62230. * To update the configuration, use the following code:
  62231. * ```javascript
  62232. * BABYLON.DracoCompression.Configuration = {
  62233. * decoder: {
  62234. * wasmUrl: "<url to the WebAssembly library>",
  62235. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62236. * fallbackUrl: "<url to the fallback JavaScript library>",
  62237. * }
  62238. * };
  62239. * ```
  62240. *
  62241. * 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.
  62242. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62243. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62244. *
  62245. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62246. * ```javascript
  62247. * var dracoCompression = new BABYLON.DracoCompression();
  62248. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62249. * [BABYLON.VertexBuffer.PositionKind]: 0
  62250. * });
  62251. * ```
  62252. *
  62253. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62254. */
  62255. var DracoCompression = /** @class */ (function () {
  62256. /**
  62257. * Constructor
  62258. */
  62259. function DracoCompression() {
  62260. }
  62261. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62262. /**
  62263. * Returns true if the decoder is available.
  62264. */
  62265. get: function () {
  62266. if (typeof DracoDecoderModule !== "undefined") {
  62267. return true;
  62268. }
  62269. var decoder = DracoCompression.Configuration.decoder;
  62270. if (decoder) {
  62271. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62272. return true;
  62273. }
  62274. if (decoder.fallbackUrl) {
  62275. return true;
  62276. }
  62277. }
  62278. return false;
  62279. },
  62280. enumerable: true,
  62281. configurable: true
  62282. });
  62283. /**
  62284. * Stop all async operations and release resources.
  62285. */
  62286. DracoCompression.prototype.dispose = function () {
  62287. };
  62288. /**
  62289. * Decode Draco compressed mesh data to vertex data.
  62290. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62291. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62292. * @returns A promise that resolves with the decoded vertex data
  62293. */
  62294. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62295. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62296. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62297. var module = wrappedModule.module;
  62298. var vertexData = new BABYLON.VertexData();
  62299. var buffer = new module.DecoderBuffer();
  62300. buffer.Init(dataView, dataView.byteLength);
  62301. var decoder = new module.Decoder();
  62302. var geometry;
  62303. var status;
  62304. try {
  62305. var type = decoder.GetEncodedGeometryType(buffer);
  62306. switch (type) {
  62307. case module.TRIANGULAR_MESH:
  62308. geometry = new module.Mesh();
  62309. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62310. break;
  62311. case module.POINT_CLOUD:
  62312. geometry = new module.PointCloud();
  62313. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62314. break;
  62315. default:
  62316. throw new Error("Invalid geometry type " + type);
  62317. }
  62318. if (!status.ok() || !geometry.ptr) {
  62319. throw new Error(status.error_msg());
  62320. }
  62321. var numPoints = geometry.num_points();
  62322. if (type === module.TRIANGULAR_MESH) {
  62323. var numFaces = geometry.num_faces();
  62324. var faceIndices = new module.DracoInt32Array();
  62325. try {
  62326. var indices = new Uint32Array(numFaces * 3);
  62327. for (var i = 0; i < numFaces; i++) {
  62328. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62329. var offset = i * 3;
  62330. indices[offset + 0] = faceIndices.GetValue(0);
  62331. indices[offset + 1] = faceIndices.GetValue(1);
  62332. indices[offset + 2] = faceIndices.GetValue(2);
  62333. }
  62334. vertexData.indices = indices;
  62335. }
  62336. finally {
  62337. module.destroy(faceIndices);
  62338. }
  62339. }
  62340. for (var kind in attributes) {
  62341. var uniqueId = attributes[kind];
  62342. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62343. var dracoData = new module.DracoFloat32Array();
  62344. try {
  62345. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62346. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62347. for (var i = 0; i < babylonData.length; i++) {
  62348. babylonData[i] = dracoData.GetValue(i);
  62349. }
  62350. vertexData.set(babylonData, kind);
  62351. }
  62352. finally {
  62353. module.destroy(dracoData);
  62354. }
  62355. }
  62356. }
  62357. finally {
  62358. if (geometry) {
  62359. module.destroy(geometry);
  62360. }
  62361. module.destroy(decoder);
  62362. module.destroy(buffer);
  62363. }
  62364. return vertexData;
  62365. });
  62366. };
  62367. DracoCompression._GetDecoderModule = function () {
  62368. if (!DracoCompression._DecoderModulePromise) {
  62369. var promise = null;
  62370. var config_1 = {};
  62371. if (typeof DracoDecoderModule !== "undefined") {
  62372. promise = Promise.resolve();
  62373. }
  62374. else {
  62375. var decoder = DracoCompression.Configuration.decoder;
  62376. if (decoder) {
  62377. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62378. promise = Promise.all([
  62379. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62380. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62381. config_1.wasmBinary = data;
  62382. })
  62383. ]);
  62384. }
  62385. else if (decoder.fallbackUrl) {
  62386. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62387. }
  62388. }
  62389. }
  62390. if (!promise) {
  62391. throw new Error("Draco decoder module is not available");
  62392. }
  62393. DracoCompression._DecoderModulePromise = promise.then(function () {
  62394. return new Promise(function (resolve) {
  62395. config_1.onModuleLoaded = function (decoderModule) {
  62396. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62397. resolve({ module: decoderModule });
  62398. };
  62399. DracoDecoderModule(config_1);
  62400. });
  62401. });
  62402. }
  62403. return DracoCompression._DecoderModulePromise;
  62404. };
  62405. DracoCompression._LoadScriptAsync = function (url) {
  62406. return new Promise(function (resolve, reject) {
  62407. BABYLON.Tools.LoadScript(url, function () {
  62408. resolve();
  62409. }, function (message) {
  62410. reject(new Error(message));
  62411. });
  62412. });
  62413. };
  62414. DracoCompression._LoadFileAsync = function (url) {
  62415. return new Promise(function (resolve, reject) {
  62416. BABYLON.Tools.LoadFile(url, function (data) {
  62417. resolve(data);
  62418. }, undefined, undefined, true, function (request, exception) {
  62419. reject(exception);
  62420. });
  62421. });
  62422. };
  62423. /**
  62424. * The configuration. Defaults to the following urls:
  62425. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62426. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62427. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62428. */
  62429. DracoCompression.Configuration = {
  62430. decoder: {
  62431. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62432. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62433. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62434. }
  62435. };
  62436. return DracoCompression;
  62437. }());
  62438. BABYLON.DracoCompression = DracoCompression;
  62439. })(BABYLON || (BABYLON = {}));
  62440. //# sourceMappingURL=babylon.dracoCompression.js.map
  62441. var BABYLON;
  62442. (function (BABYLON) {
  62443. var AudioEngine = /** @class */ (function () {
  62444. function AudioEngine() {
  62445. this._audioContext = null;
  62446. this._audioContextInitialized = false;
  62447. this.canUseWebAudio = false;
  62448. this.WarnedWebAudioUnsupported = false;
  62449. this.unlocked = false;
  62450. this.isMP3supported = false;
  62451. this.isOGGsupported = false;
  62452. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62453. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62454. this.canUseWebAudio = true;
  62455. }
  62456. var audioElem = document.createElement('audio');
  62457. try {
  62458. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62459. this.isMP3supported = true;
  62460. }
  62461. }
  62462. catch (e) {
  62463. // protect error during capability check.
  62464. }
  62465. try {
  62466. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62467. this.isOGGsupported = true;
  62468. }
  62469. }
  62470. catch (e) {
  62471. // protect error during capability check.
  62472. }
  62473. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62474. this._unlockiOSaudio();
  62475. }
  62476. else {
  62477. this.unlocked = true;
  62478. }
  62479. }
  62480. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62481. get: function () {
  62482. if (!this._audioContextInitialized) {
  62483. this._initializeAudioContext();
  62484. }
  62485. return this._audioContext;
  62486. },
  62487. enumerable: true,
  62488. configurable: true
  62489. });
  62490. AudioEngine.prototype._unlockiOSaudio = function () {
  62491. var _this = this;
  62492. var unlockaudio = function () {
  62493. if (!_this.audioContext) {
  62494. return;
  62495. }
  62496. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62497. var source = _this.audioContext.createBufferSource();
  62498. source.buffer = buffer;
  62499. source.connect(_this.audioContext.destination);
  62500. source.start(0);
  62501. setTimeout(function () {
  62502. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62503. _this.unlocked = true;
  62504. window.removeEventListener('touchend', unlockaudio, false);
  62505. if (_this.onAudioUnlocked) {
  62506. _this.onAudioUnlocked();
  62507. }
  62508. }
  62509. }, 0);
  62510. };
  62511. window.addEventListener('touchend', unlockaudio, false);
  62512. };
  62513. AudioEngine.prototype._initializeAudioContext = function () {
  62514. try {
  62515. if (this.canUseWebAudio) {
  62516. this._audioContext = new AudioContext();
  62517. // create a global volume gain node
  62518. this.masterGain = this._audioContext.createGain();
  62519. this.masterGain.gain.value = 1;
  62520. this.masterGain.connect(this._audioContext.destination);
  62521. this._audioContextInitialized = true;
  62522. }
  62523. }
  62524. catch (e) {
  62525. this.canUseWebAudio = false;
  62526. BABYLON.Tools.Error("Web Audio: " + e.message);
  62527. }
  62528. };
  62529. AudioEngine.prototype.dispose = function () {
  62530. if (this.canUseWebAudio && this._audioContextInitialized) {
  62531. if (this._connectedAnalyser && this._audioContext) {
  62532. this._connectedAnalyser.stopDebugCanvas();
  62533. this._connectedAnalyser.dispose();
  62534. this.masterGain.disconnect();
  62535. this.masterGain.connect(this._audioContext.destination);
  62536. this._connectedAnalyser = null;
  62537. }
  62538. this.masterGain.gain.value = 1;
  62539. }
  62540. this.WarnedWebAudioUnsupported = false;
  62541. };
  62542. AudioEngine.prototype.getGlobalVolume = function () {
  62543. if (this.canUseWebAudio && this._audioContextInitialized) {
  62544. return this.masterGain.gain.value;
  62545. }
  62546. else {
  62547. return -1;
  62548. }
  62549. };
  62550. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62551. if (this.canUseWebAudio && this._audioContextInitialized) {
  62552. this.masterGain.gain.value = newVolume;
  62553. }
  62554. };
  62555. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62556. if (this._connectedAnalyser) {
  62557. this._connectedAnalyser.stopDebugCanvas();
  62558. }
  62559. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62560. this._connectedAnalyser = analyser;
  62561. this.masterGain.disconnect();
  62562. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62563. }
  62564. };
  62565. return AudioEngine;
  62566. }());
  62567. BABYLON.AudioEngine = AudioEngine;
  62568. })(BABYLON || (BABYLON = {}));
  62569. //# sourceMappingURL=babylon.audioEngine.js.map
  62570. var BABYLON;
  62571. (function (BABYLON) {
  62572. var Sound = /** @class */ (function () {
  62573. /**
  62574. * Create a sound and attach it to a scene
  62575. * @param name Name of your sound
  62576. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62577. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62578. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62579. */
  62580. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62581. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62582. var _this = this;
  62583. this.autoplay = false;
  62584. this.loop = false;
  62585. this.useCustomAttenuation = false;
  62586. this.spatialSound = false;
  62587. this.refDistance = 1;
  62588. this.rolloffFactor = 1;
  62589. this.maxDistance = 100;
  62590. this.distanceModel = "linear";
  62591. this._panningModel = "equalpower";
  62592. this._playbackRate = 1;
  62593. this._streaming = false;
  62594. this._startTime = 0;
  62595. this._startOffset = 0;
  62596. this._position = BABYLON.Vector3.Zero();
  62597. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62598. this._volume = 1;
  62599. this._isReadyToPlay = false;
  62600. this.isPlaying = false;
  62601. this.isPaused = false;
  62602. this._isDirectional = false;
  62603. // Used if you'd like to create a directional sound.
  62604. // If not set, the sound will be omnidirectional
  62605. this._coneInnerAngle = 360;
  62606. this._coneOuterAngle = 360;
  62607. this._coneOuterGain = 0;
  62608. this._isOutputConnected = false;
  62609. this._urlType = "Unknown";
  62610. this.name = name;
  62611. this._scene = scene;
  62612. this._readyToPlayCallback = readyToPlayCallback;
  62613. // Default custom attenuation function is a linear attenuation
  62614. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62615. if (currentDistance < maxDistance) {
  62616. return currentVolume * (1 - currentDistance / maxDistance);
  62617. }
  62618. else {
  62619. return 0;
  62620. }
  62621. };
  62622. if (options) {
  62623. this.autoplay = options.autoplay || false;
  62624. this.loop = options.loop || false;
  62625. // if volume === 0, we need another way to check this option
  62626. if (options.volume !== undefined) {
  62627. this._volume = options.volume;
  62628. }
  62629. this.spatialSound = options.spatialSound || false;
  62630. this.maxDistance = options.maxDistance || 100;
  62631. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62632. this.rolloffFactor = options.rolloffFactor || 1;
  62633. this.refDistance = options.refDistance || 1;
  62634. this.distanceModel = options.distanceModel || "linear";
  62635. this._playbackRate = options.playbackRate || 1;
  62636. this._streaming = options.streaming || false;
  62637. }
  62638. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62639. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62640. this._soundGain.gain.value = this._volume;
  62641. this._inputAudioNode = this._soundGain;
  62642. this._ouputAudioNode = this._soundGain;
  62643. if (this.spatialSound) {
  62644. this._createSpatialParameters();
  62645. }
  62646. this._scene.mainSoundTrack.AddSound(this);
  62647. var validParameter = true;
  62648. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62649. if (urlOrArrayBuffer) {
  62650. try {
  62651. if (typeof (urlOrArrayBuffer) === "string") {
  62652. this._urlType = "String";
  62653. }
  62654. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62655. this._urlType = "ArrayBuffer";
  62656. }
  62657. else if (urlOrArrayBuffer instanceof MediaStream) {
  62658. this._urlType = "MediaStream";
  62659. }
  62660. else if (Array.isArray(urlOrArrayBuffer)) {
  62661. this._urlType = "Array";
  62662. }
  62663. var urls = [];
  62664. var codecSupportedFound = false;
  62665. switch (this._urlType) {
  62666. case "MediaStream":
  62667. this._streaming = true;
  62668. this._isReadyToPlay = true;
  62669. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62670. if (this.autoplay) {
  62671. this.play();
  62672. }
  62673. if (this._readyToPlayCallback) {
  62674. this._readyToPlayCallback();
  62675. }
  62676. break;
  62677. case "ArrayBuffer":
  62678. if (urlOrArrayBuffer.byteLength > 0) {
  62679. codecSupportedFound = true;
  62680. this._soundLoaded(urlOrArrayBuffer);
  62681. }
  62682. break;
  62683. case "String":
  62684. urls.push(urlOrArrayBuffer);
  62685. case "Array":
  62686. if (urls.length === 0)
  62687. urls = urlOrArrayBuffer;
  62688. // If we found a supported format, we load it immediately and stop the loop
  62689. for (var i = 0; i < urls.length; i++) {
  62690. var url = urls[i];
  62691. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62692. codecSupportedFound = true;
  62693. }
  62694. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62695. codecSupportedFound = true;
  62696. }
  62697. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62698. codecSupportedFound = true;
  62699. }
  62700. if (url.indexOf("blob:") !== -1) {
  62701. codecSupportedFound = true;
  62702. }
  62703. if (codecSupportedFound) {
  62704. // Loading sound using XHR2
  62705. if (!this._streaming) {
  62706. this._scene._loadFile(url, function (data) {
  62707. _this._soundLoaded(data);
  62708. }, undefined, true, true, function (exception) {
  62709. if (exception) {
  62710. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62711. }
  62712. BABYLON.Tools.Error("Sound creation aborted.");
  62713. _this._scene.mainSoundTrack.RemoveSound(_this);
  62714. });
  62715. }
  62716. // Streaming sound using HTML5 Audio tag
  62717. else {
  62718. this._htmlAudioElement = new Audio(url);
  62719. this._htmlAudioElement.controls = false;
  62720. this._htmlAudioElement.loop = this.loop;
  62721. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62722. this._htmlAudioElement.preload = "auto";
  62723. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62724. _this._isReadyToPlay = true;
  62725. if (_this.autoplay) {
  62726. _this.play();
  62727. }
  62728. if (_this._readyToPlayCallback) {
  62729. _this._readyToPlayCallback();
  62730. }
  62731. });
  62732. document.body.appendChild(this._htmlAudioElement);
  62733. }
  62734. break;
  62735. }
  62736. }
  62737. break;
  62738. default:
  62739. validParameter = false;
  62740. break;
  62741. }
  62742. if (!validParameter) {
  62743. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62744. }
  62745. else {
  62746. if (!codecSupportedFound) {
  62747. this._isReadyToPlay = true;
  62748. // Simulating a ready to play event to avoid breaking code path
  62749. if (this._readyToPlayCallback) {
  62750. window.setTimeout(function () {
  62751. if (_this._readyToPlayCallback) {
  62752. _this._readyToPlayCallback();
  62753. }
  62754. }, 1000);
  62755. }
  62756. }
  62757. }
  62758. }
  62759. catch (ex) {
  62760. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62761. this._scene.mainSoundTrack.RemoveSound(this);
  62762. }
  62763. }
  62764. }
  62765. else {
  62766. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62767. this._scene.mainSoundTrack.AddSound(this);
  62768. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62769. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62770. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62771. }
  62772. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62773. if (this._readyToPlayCallback) {
  62774. window.setTimeout(function () {
  62775. if (_this._readyToPlayCallback) {
  62776. _this._readyToPlayCallback();
  62777. }
  62778. }, 1000);
  62779. }
  62780. }
  62781. }
  62782. Sound.prototype.dispose = function () {
  62783. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62784. if (this.isPlaying) {
  62785. this.stop();
  62786. }
  62787. this._isReadyToPlay = false;
  62788. if (this.soundTrackId === -1) {
  62789. this._scene.mainSoundTrack.RemoveSound(this);
  62790. }
  62791. else {
  62792. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62793. }
  62794. if (this._soundGain) {
  62795. this._soundGain.disconnect();
  62796. this._soundGain = null;
  62797. }
  62798. if (this._soundPanner) {
  62799. this._soundPanner.disconnect();
  62800. this._soundPanner = null;
  62801. }
  62802. if (this._soundSource) {
  62803. this._soundSource.disconnect();
  62804. this._soundSource = null;
  62805. }
  62806. this._audioBuffer = null;
  62807. if (this._htmlAudioElement) {
  62808. this._htmlAudioElement.pause();
  62809. this._htmlAudioElement.src = "";
  62810. document.body.removeChild(this._htmlAudioElement);
  62811. }
  62812. if (this._streamingSource) {
  62813. this._streamingSource.disconnect();
  62814. }
  62815. if (this._connectedMesh && this._registerFunc) {
  62816. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62817. this._connectedMesh = null;
  62818. }
  62819. }
  62820. };
  62821. Sound.prototype.isReady = function () {
  62822. return this._isReadyToPlay;
  62823. };
  62824. Sound.prototype._soundLoaded = function (audioData) {
  62825. var _this = this;
  62826. if (!BABYLON.Engine.audioEngine.audioContext) {
  62827. return;
  62828. }
  62829. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62830. _this._audioBuffer = buffer;
  62831. _this._isReadyToPlay = true;
  62832. if (_this.autoplay) {
  62833. _this.play();
  62834. }
  62835. if (_this._readyToPlayCallback) {
  62836. _this._readyToPlayCallback();
  62837. }
  62838. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62839. };
  62840. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62841. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62842. this._audioBuffer = audioBuffer;
  62843. this._isReadyToPlay = true;
  62844. }
  62845. };
  62846. Sound.prototype.updateOptions = function (options) {
  62847. if (options) {
  62848. this.loop = options.loop || this.loop;
  62849. this.maxDistance = options.maxDistance || this.maxDistance;
  62850. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62851. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62852. this.refDistance = options.refDistance || this.refDistance;
  62853. this.distanceModel = options.distanceModel || this.distanceModel;
  62854. this._playbackRate = options.playbackRate || this._playbackRate;
  62855. this._updateSpatialParameters();
  62856. if (this.isPlaying) {
  62857. if (this._streaming && this._htmlAudioElement) {
  62858. this._htmlAudioElement.playbackRate = this._playbackRate;
  62859. }
  62860. else {
  62861. if (this._soundSource) {
  62862. this._soundSource.playbackRate.value = this._playbackRate;
  62863. }
  62864. }
  62865. }
  62866. }
  62867. };
  62868. Sound.prototype._createSpatialParameters = function () {
  62869. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62870. if (this._scene.headphone) {
  62871. this._panningModel = "HRTF";
  62872. }
  62873. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62874. this._updateSpatialParameters();
  62875. this._soundPanner.connect(this._ouputAudioNode);
  62876. this._inputAudioNode = this._soundPanner;
  62877. }
  62878. };
  62879. Sound.prototype._updateSpatialParameters = function () {
  62880. if (this.spatialSound && this._soundPanner) {
  62881. if (this.useCustomAttenuation) {
  62882. // Tricks to disable in a way embedded Web Audio attenuation
  62883. this._soundPanner.distanceModel = "linear";
  62884. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62885. this._soundPanner.refDistance = 1;
  62886. this._soundPanner.rolloffFactor = 1;
  62887. this._soundPanner.panningModel = this._panningModel;
  62888. }
  62889. else {
  62890. this._soundPanner.distanceModel = this.distanceModel;
  62891. this._soundPanner.maxDistance = this.maxDistance;
  62892. this._soundPanner.refDistance = this.refDistance;
  62893. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62894. this._soundPanner.panningModel = this._panningModel;
  62895. }
  62896. }
  62897. };
  62898. Sound.prototype.switchPanningModelToHRTF = function () {
  62899. this._panningModel = "HRTF";
  62900. this._switchPanningModel();
  62901. };
  62902. Sound.prototype.switchPanningModelToEqualPower = function () {
  62903. this._panningModel = "equalpower";
  62904. this._switchPanningModel();
  62905. };
  62906. Sound.prototype._switchPanningModel = function () {
  62907. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62908. this._soundPanner.panningModel = this._panningModel;
  62909. }
  62910. };
  62911. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62912. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62913. if (this._isOutputConnected) {
  62914. this._ouputAudioNode.disconnect();
  62915. }
  62916. this._ouputAudioNode.connect(soundTrackAudioNode);
  62917. this._isOutputConnected = true;
  62918. }
  62919. };
  62920. /**
  62921. * Transform this sound into a directional source
  62922. * @param coneInnerAngle Size of the inner cone in degree
  62923. * @param coneOuterAngle Size of the outer cone in degree
  62924. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62925. */
  62926. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62927. if (coneOuterAngle < coneInnerAngle) {
  62928. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62929. return;
  62930. }
  62931. this._coneInnerAngle = coneInnerAngle;
  62932. this._coneOuterAngle = coneOuterAngle;
  62933. this._coneOuterGain = coneOuterGain;
  62934. this._isDirectional = true;
  62935. if (this.isPlaying && this.loop) {
  62936. this.stop();
  62937. this.play();
  62938. }
  62939. };
  62940. Sound.prototype.setPosition = function (newPosition) {
  62941. this._position = newPosition;
  62942. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62943. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62944. }
  62945. };
  62946. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62947. this._localDirection = newLocalDirection;
  62948. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62949. this._updateDirection();
  62950. }
  62951. };
  62952. Sound.prototype._updateDirection = function () {
  62953. if (!this._connectedMesh || !this._soundPanner) {
  62954. return;
  62955. }
  62956. var mat = this._connectedMesh.getWorldMatrix();
  62957. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62958. direction.normalize();
  62959. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62960. };
  62961. Sound.prototype.updateDistanceFromListener = function () {
  62962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62963. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62964. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62965. }
  62966. };
  62967. Sound.prototype.setAttenuationFunction = function (callback) {
  62968. this._customAttenuationFunction = callback;
  62969. };
  62970. /**
  62971. * Play the sound
  62972. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62973. * @param offset (optional) Start the sound setting it at a specific time
  62974. */
  62975. Sound.prototype.play = function (time, offset) {
  62976. var _this = this;
  62977. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62978. try {
  62979. if (this._startOffset < 0) {
  62980. time = -this._startOffset;
  62981. this._startOffset = 0;
  62982. }
  62983. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62984. if (!this._soundSource || !this._streamingSource) {
  62985. if (this.spatialSound && this._soundPanner) {
  62986. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62987. if (this._isDirectional) {
  62988. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62989. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62990. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62991. if (this._connectedMesh) {
  62992. this._updateDirection();
  62993. }
  62994. else {
  62995. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62996. }
  62997. }
  62998. }
  62999. }
  63000. if (this._streaming) {
  63001. if (!this._streamingSource) {
  63002. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63003. this._htmlAudioElement.onended = function () { _this._onended(); };
  63004. this._htmlAudioElement.playbackRate = this._playbackRate;
  63005. }
  63006. this._streamingSource.disconnect();
  63007. this._streamingSource.connect(this._inputAudioNode);
  63008. if (this._htmlAudioElement) {
  63009. this._htmlAudioElement.play();
  63010. }
  63011. }
  63012. else {
  63013. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63014. this._soundSource.buffer = this._audioBuffer;
  63015. this._soundSource.connect(this._inputAudioNode);
  63016. this._soundSource.loop = this.loop;
  63017. this._soundSource.playbackRate.value = this._playbackRate;
  63018. this._soundSource.onended = function () { _this._onended(); };
  63019. if (this._soundSource.buffer) {
  63020. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63021. }
  63022. }
  63023. this._startTime = startTime;
  63024. this.isPlaying = true;
  63025. this.isPaused = false;
  63026. }
  63027. catch (ex) {
  63028. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63029. }
  63030. }
  63031. };
  63032. Sound.prototype._onended = function () {
  63033. this.isPlaying = false;
  63034. if (this.onended) {
  63035. this.onended();
  63036. }
  63037. };
  63038. /**
  63039. * Stop the sound
  63040. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63041. */
  63042. Sound.prototype.stop = function (time) {
  63043. if (this.isPlaying) {
  63044. if (this._streaming) {
  63045. if (this._htmlAudioElement) {
  63046. this._htmlAudioElement.pause();
  63047. // Test needed for Firefox or it will generate an Invalid State Error
  63048. if (this._htmlAudioElement.currentTime > 0) {
  63049. this._htmlAudioElement.currentTime = 0;
  63050. }
  63051. }
  63052. else {
  63053. this._streamingSource.disconnect();
  63054. }
  63055. }
  63056. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63057. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63058. this._soundSource.stop(stopTime);
  63059. this._soundSource.onended = function () { };
  63060. if (!this.isPaused) {
  63061. this._startOffset = 0;
  63062. }
  63063. }
  63064. this.isPlaying = false;
  63065. }
  63066. };
  63067. Sound.prototype.pause = function () {
  63068. if (this.isPlaying) {
  63069. this.isPaused = true;
  63070. if (this._streaming) {
  63071. if (this._htmlAudioElement) {
  63072. this._htmlAudioElement.pause();
  63073. }
  63074. else {
  63075. this._streamingSource.disconnect();
  63076. }
  63077. }
  63078. else if (BABYLON.Engine.audioEngine.audioContext) {
  63079. this.stop(0);
  63080. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63081. }
  63082. }
  63083. };
  63084. Sound.prototype.setVolume = function (newVolume, time) {
  63085. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63086. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63087. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63088. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63089. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63090. }
  63091. else {
  63092. this._soundGain.gain.value = newVolume;
  63093. }
  63094. }
  63095. this._volume = newVolume;
  63096. };
  63097. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63098. this._playbackRate = newPlaybackRate;
  63099. if (this.isPlaying) {
  63100. if (this._streaming && this._htmlAudioElement) {
  63101. this._htmlAudioElement.playbackRate = this._playbackRate;
  63102. }
  63103. else if (this._soundSource) {
  63104. this._soundSource.playbackRate.value = this._playbackRate;
  63105. }
  63106. }
  63107. };
  63108. Sound.prototype.getVolume = function () {
  63109. return this._volume;
  63110. };
  63111. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63112. var _this = this;
  63113. if (this._connectedMesh && this._registerFunc) {
  63114. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63115. this._registerFunc = null;
  63116. }
  63117. this._connectedMesh = meshToConnectTo;
  63118. if (!this.spatialSound) {
  63119. this.spatialSound = true;
  63120. this._createSpatialParameters();
  63121. if (this.isPlaying && this.loop) {
  63122. this.stop();
  63123. this.play();
  63124. }
  63125. }
  63126. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63127. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63128. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63129. };
  63130. Sound.prototype.detachFromMesh = function () {
  63131. if (this._connectedMesh && this._registerFunc) {
  63132. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63133. this._registerFunc = null;
  63134. this._connectedMesh = null;
  63135. }
  63136. };
  63137. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63138. if (!node.getBoundingInfo) {
  63139. return;
  63140. }
  63141. var mesh = node;
  63142. var boundingInfo = mesh.getBoundingInfo();
  63143. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63144. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63145. this._updateDirection();
  63146. }
  63147. };
  63148. Sound.prototype.clone = function () {
  63149. var _this = this;
  63150. if (!this._streaming) {
  63151. var setBufferAndRun = function () {
  63152. if (_this._isReadyToPlay) {
  63153. clonedSound._audioBuffer = _this.getAudioBuffer();
  63154. clonedSound._isReadyToPlay = true;
  63155. if (clonedSound.autoplay) {
  63156. clonedSound.play();
  63157. }
  63158. }
  63159. else {
  63160. window.setTimeout(setBufferAndRun, 300);
  63161. }
  63162. };
  63163. var currentOptions = {
  63164. autoplay: this.autoplay, loop: this.loop,
  63165. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63166. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63167. refDistance: this.refDistance, distanceModel: this.distanceModel
  63168. };
  63169. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63170. if (this.useCustomAttenuation) {
  63171. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63172. }
  63173. clonedSound.setPosition(this._position);
  63174. clonedSound.setPlaybackRate(this._playbackRate);
  63175. setBufferAndRun();
  63176. return clonedSound;
  63177. }
  63178. // Can't clone a streaming sound
  63179. else {
  63180. return null;
  63181. }
  63182. };
  63183. Sound.prototype.getAudioBuffer = function () {
  63184. return this._audioBuffer;
  63185. };
  63186. Sound.prototype.serialize = function () {
  63187. var serializationObject = {
  63188. name: this.name,
  63189. url: this.name,
  63190. autoplay: this.autoplay,
  63191. loop: this.loop,
  63192. volume: this._volume,
  63193. spatialSound: this.spatialSound,
  63194. maxDistance: this.maxDistance,
  63195. rolloffFactor: this.rolloffFactor,
  63196. refDistance: this.refDistance,
  63197. distanceModel: this.distanceModel,
  63198. playbackRate: this._playbackRate,
  63199. panningModel: this._panningModel,
  63200. soundTrackId: this.soundTrackId
  63201. };
  63202. if (this.spatialSound) {
  63203. if (this._connectedMesh)
  63204. serializationObject.connectedMeshId = this._connectedMesh.id;
  63205. serializationObject.position = this._position.asArray();
  63206. serializationObject.refDistance = this.refDistance;
  63207. serializationObject.distanceModel = this.distanceModel;
  63208. serializationObject.isDirectional = this._isDirectional;
  63209. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63210. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63211. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63212. serializationObject.coneOuterGain = this._coneOuterGain;
  63213. }
  63214. return serializationObject;
  63215. };
  63216. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63217. var soundName = parsedSound.name;
  63218. var soundUrl;
  63219. if (parsedSound.url) {
  63220. soundUrl = rootUrl + parsedSound.url;
  63221. }
  63222. else {
  63223. soundUrl = rootUrl + soundName;
  63224. }
  63225. var options = {
  63226. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63227. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63228. rolloffFactor: parsedSound.rolloffFactor,
  63229. refDistance: parsedSound.refDistance,
  63230. distanceModel: parsedSound.distanceModel,
  63231. playbackRate: parsedSound.playbackRate
  63232. };
  63233. var newSound;
  63234. if (!sourceSound) {
  63235. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63236. scene._addPendingData(newSound);
  63237. }
  63238. else {
  63239. var setBufferAndRun = function () {
  63240. if (sourceSound._isReadyToPlay) {
  63241. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63242. newSound._isReadyToPlay = true;
  63243. if (newSound.autoplay) {
  63244. newSound.play();
  63245. }
  63246. }
  63247. else {
  63248. window.setTimeout(setBufferAndRun, 300);
  63249. }
  63250. };
  63251. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63252. setBufferAndRun();
  63253. }
  63254. if (parsedSound.position) {
  63255. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63256. newSound.setPosition(soundPosition);
  63257. }
  63258. if (parsedSound.isDirectional) {
  63259. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63260. if (parsedSound.localDirectionToMesh) {
  63261. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63262. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63263. }
  63264. }
  63265. if (parsedSound.connectedMeshId) {
  63266. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63267. if (connectedMesh) {
  63268. newSound.attachToMesh(connectedMesh);
  63269. }
  63270. }
  63271. return newSound;
  63272. };
  63273. return Sound;
  63274. }());
  63275. BABYLON.Sound = Sound;
  63276. })(BABYLON || (BABYLON = {}));
  63277. //# sourceMappingURL=babylon.sound.js.map
  63278. var BABYLON;
  63279. (function (BABYLON) {
  63280. var SoundTrack = /** @class */ (function () {
  63281. function SoundTrack(scene, options) {
  63282. this.id = -1;
  63283. this._isMainTrack = false;
  63284. this._isInitialized = false;
  63285. this._scene = scene;
  63286. this.soundCollection = new Array();
  63287. this._options = options;
  63288. if (!this._isMainTrack) {
  63289. this._scene.soundTracks.push(this);
  63290. this.id = this._scene.soundTracks.length - 1;
  63291. }
  63292. }
  63293. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63294. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63295. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63296. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63297. if (this._options) {
  63298. if (this._options.volume) {
  63299. this._outputAudioNode.gain.value = this._options.volume;
  63300. }
  63301. if (this._options.mainTrack) {
  63302. this._isMainTrack = this._options.mainTrack;
  63303. }
  63304. }
  63305. this._isInitialized = true;
  63306. }
  63307. };
  63308. SoundTrack.prototype.dispose = function () {
  63309. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63310. if (this._connectedAnalyser) {
  63311. this._connectedAnalyser.stopDebugCanvas();
  63312. }
  63313. while (this.soundCollection.length) {
  63314. this.soundCollection[0].dispose();
  63315. }
  63316. if (this._outputAudioNode) {
  63317. this._outputAudioNode.disconnect();
  63318. }
  63319. this._outputAudioNode = null;
  63320. }
  63321. };
  63322. SoundTrack.prototype.AddSound = function (sound) {
  63323. if (!this._isInitialized) {
  63324. this._initializeSoundTrackAudioGraph();
  63325. }
  63326. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63327. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63328. }
  63329. if (sound.soundTrackId) {
  63330. if (sound.soundTrackId === -1) {
  63331. this._scene.mainSoundTrack.RemoveSound(sound);
  63332. }
  63333. else {
  63334. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63335. }
  63336. }
  63337. this.soundCollection.push(sound);
  63338. sound.soundTrackId = this.id;
  63339. };
  63340. SoundTrack.prototype.RemoveSound = function (sound) {
  63341. var index = this.soundCollection.indexOf(sound);
  63342. if (index !== -1) {
  63343. this.soundCollection.splice(index, 1);
  63344. }
  63345. };
  63346. SoundTrack.prototype.setVolume = function (newVolume) {
  63347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63348. this._outputAudioNode.gain.value = newVolume;
  63349. }
  63350. };
  63351. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63353. for (var i = 0; i < this.soundCollection.length; i++) {
  63354. this.soundCollection[i].switchPanningModelToHRTF();
  63355. }
  63356. }
  63357. };
  63358. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63359. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63360. for (var i = 0; i < this.soundCollection.length; i++) {
  63361. this.soundCollection[i].switchPanningModelToEqualPower();
  63362. }
  63363. }
  63364. };
  63365. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63366. if (this._connectedAnalyser) {
  63367. this._connectedAnalyser.stopDebugCanvas();
  63368. }
  63369. this._connectedAnalyser = analyser;
  63370. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63371. this._outputAudioNode.disconnect();
  63372. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63373. }
  63374. };
  63375. return SoundTrack;
  63376. }());
  63377. BABYLON.SoundTrack = SoundTrack;
  63378. })(BABYLON || (BABYLON = {}));
  63379. //# sourceMappingURL=babylon.soundtrack.js.map
  63380. var BABYLON;
  63381. (function (BABYLON) {
  63382. /**
  63383. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63384. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63385. */
  63386. var Analyser = /** @class */ (function () {
  63387. /**
  63388. * Creates a new analyser
  63389. * @param scene defines hosting scene
  63390. */
  63391. function Analyser(scene) {
  63392. /**
  63393. * Gets or sets the smoothing
  63394. * @ignorenaming
  63395. */
  63396. this.SMOOTHING = 0.75;
  63397. /**
  63398. * Gets or sets the FFT table size
  63399. * @ignorenaming
  63400. */
  63401. this.FFT_SIZE = 512;
  63402. /**
  63403. * Gets or sets the bar graph amplitude
  63404. * @ignorenaming
  63405. */
  63406. this.BARGRAPHAMPLITUDE = 256;
  63407. /**
  63408. * Gets or sets the position of the debug canvas
  63409. * @ignorenaming
  63410. */
  63411. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63412. /**
  63413. * Gets or sets the debug canvas size
  63414. * @ignorenaming
  63415. */
  63416. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63417. this._scene = scene;
  63418. this._audioEngine = BABYLON.Engine.audioEngine;
  63419. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63420. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63421. this._webAudioAnalyser.minDecibels = -140;
  63422. this._webAudioAnalyser.maxDecibels = 0;
  63423. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63424. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63425. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63426. }
  63427. }
  63428. /**
  63429. * Get the number of data values you will have to play with for the visualization
  63430. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63431. * @returns a number
  63432. */
  63433. Analyser.prototype.getFrequencyBinCount = function () {
  63434. if (this._audioEngine.canUseWebAudio) {
  63435. return this._webAudioAnalyser.frequencyBinCount;
  63436. }
  63437. else {
  63438. return 0;
  63439. }
  63440. };
  63441. /**
  63442. * Gets the current frequency data as a byte array
  63443. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63444. * @returns a Uint8Array
  63445. */
  63446. Analyser.prototype.getByteFrequencyData = function () {
  63447. if (this._audioEngine.canUseWebAudio) {
  63448. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63449. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63450. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63451. }
  63452. return this._byteFreqs;
  63453. };
  63454. /**
  63455. * Gets the current waveform as a byte array
  63456. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63457. * @returns a Uint8Array
  63458. */
  63459. Analyser.prototype.getByteTimeDomainData = function () {
  63460. if (this._audioEngine.canUseWebAudio) {
  63461. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63462. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63463. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63464. }
  63465. return this._byteTime;
  63466. };
  63467. /**
  63468. * Gets the current frequency data as a float array
  63469. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63470. * @returns a Float32Array
  63471. */
  63472. Analyser.prototype.getFloatFrequencyData = function () {
  63473. if (this._audioEngine.canUseWebAudio) {
  63474. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63475. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63476. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63477. }
  63478. return this._floatFreqs;
  63479. };
  63480. /**
  63481. * Renders the debug canvas
  63482. */
  63483. Analyser.prototype.drawDebugCanvas = function () {
  63484. var _this = this;
  63485. if (this._audioEngine.canUseWebAudio) {
  63486. if (!this._debugCanvas) {
  63487. this._debugCanvas = document.createElement("canvas");
  63488. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63489. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63490. this._debugCanvas.style.position = "absolute";
  63491. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63492. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63493. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63494. document.body.appendChild(this._debugCanvas);
  63495. this._registerFunc = function () {
  63496. _this.drawDebugCanvas();
  63497. };
  63498. this._scene.registerBeforeRender(this._registerFunc);
  63499. }
  63500. if (this._registerFunc && this._debugCanvasContext) {
  63501. var workingArray = this.getByteFrequencyData();
  63502. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63503. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63504. // Draw the frequency domain chart.
  63505. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63506. var value = workingArray[i];
  63507. var percent = value / this.BARGRAPHAMPLITUDE;
  63508. var height = this.DEBUGCANVASSIZE.height * percent;
  63509. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63510. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63511. var hue = i / this.getFrequencyBinCount() * 360;
  63512. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63513. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63514. }
  63515. }
  63516. }
  63517. };
  63518. /**
  63519. * Stops rendering the debug canvas and removes it
  63520. */
  63521. Analyser.prototype.stopDebugCanvas = function () {
  63522. if (this._debugCanvas) {
  63523. if (this._registerFunc) {
  63524. this._scene.unregisterBeforeRender(this._registerFunc);
  63525. this._registerFunc = null;
  63526. }
  63527. document.body.removeChild(this._debugCanvas);
  63528. this._debugCanvas = null;
  63529. this._debugCanvasContext = null;
  63530. }
  63531. };
  63532. /**
  63533. * Connects two audio nodes
  63534. * @param inputAudioNode defines first node to connect
  63535. * @param outputAudioNode defines second node to connect
  63536. */
  63537. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63538. if (this._audioEngine.canUseWebAudio) {
  63539. inputAudioNode.connect(this._webAudioAnalyser);
  63540. this._webAudioAnalyser.connect(outputAudioNode);
  63541. }
  63542. };
  63543. /**
  63544. * Releases all associated resources
  63545. */
  63546. Analyser.prototype.dispose = function () {
  63547. if (this._audioEngine.canUseWebAudio) {
  63548. this._webAudioAnalyser.disconnect();
  63549. }
  63550. };
  63551. return Analyser;
  63552. }());
  63553. BABYLON.Analyser = Analyser;
  63554. })(BABYLON || (BABYLON = {}));
  63555. //# sourceMappingURL=babylon.analyser.js.map
  63556. var BABYLON;
  63557. (function (BABYLON) {
  63558. var CubeTexture = /** @class */ (function (_super) {
  63559. __extends(CubeTexture, _super);
  63560. /**
  63561. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63562. * as prefiltered data.
  63563. * @param rootUrl defines the url of the texture or the root name of the six images
  63564. * @param scene defines the scene the texture is attached to
  63565. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63566. * @param noMipmap defines if mipmaps should be created or not
  63567. * @param files defines the six files to load for the different faces
  63568. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63569. * @param onError defines a callback triggered in case of error during load
  63570. * @param format defines the internal format to use for the texture once loaded
  63571. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63572. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63573. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63574. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63575. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63576. * @return the cube texture
  63577. */
  63578. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63579. if (extensions === void 0) { extensions = null; }
  63580. if (noMipmap === void 0) { noMipmap = false; }
  63581. if (files === void 0) { files = null; }
  63582. if (onLoad === void 0) { onLoad = null; }
  63583. if (onError === void 0) { onError = null; }
  63584. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63585. if (prefiltered === void 0) { prefiltered = false; }
  63586. if (forcedExtension === void 0) { forcedExtension = null; }
  63587. if (createPolynomials === void 0) { createPolynomials = false; }
  63588. if (lodScale === void 0) { lodScale = 0.8; }
  63589. if (lodOffset === void 0) { lodOffset = 0; }
  63590. var _this = _super.call(this, scene) || this;
  63591. /**
  63592. * Gets or sets the center of the bounding box associated with the cube texture
  63593. * It must define where the camera used to render the texture was set
  63594. */
  63595. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63596. _this._rotationY = 0;
  63597. /** @hidden */
  63598. _this._prefiltered = false;
  63599. _this.name = rootUrl;
  63600. _this.url = rootUrl;
  63601. _this._noMipmap = noMipmap;
  63602. _this.hasAlpha = false;
  63603. _this._format = format;
  63604. _this.isCube = true;
  63605. _this._textureMatrix = BABYLON.Matrix.Identity();
  63606. _this._createPolynomials = createPolynomials;
  63607. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63608. if (!rootUrl && !files) {
  63609. return _this;
  63610. }
  63611. var lastDot = rootUrl.lastIndexOf(".");
  63612. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63613. var isDDS = (extension === ".dds");
  63614. var isEnv = (extension === ".env");
  63615. if (isEnv) {
  63616. _this.gammaSpace = false;
  63617. _this._prefiltered = false;
  63618. }
  63619. else {
  63620. _this._prefiltered = prefiltered;
  63621. if (prefiltered) {
  63622. _this.gammaSpace = false;
  63623. }
  63624. }
  63625. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63626. if (!files) {
  63627. if (!isEnv && !isDDS && !extensions) {
  63628. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63629. }
  63630. files = [];
  63631. if (extensions) {
  63632. for (var index = 0; index < extensions.length; index++) {
  63633. files.push(rootUrl + extensions[index]);
  63634. }
  63635. }
  63636. }
  63637. _this._files = files;
  63638. if (!_this._texture) {
  63639. if (!scene.useDelayedTextureLoading) {
  63640. if (prefiltered) {
  63641. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63642. }
  63643. else {
  63644. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63645. }
  63646. }
  63647. else {
  63648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63649. }
  63650. }
  63651. else if (onLoad) {
  63652. if (_this._texture.isReady) {
  63653. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63654. }
  63655. else {
  63656. _this._texture.onLoadedObservable.add(onLoad);
  63657. }
  63658. }
  63659. return _this;
  63660. }
  63661. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63662. get: function () {
  63663. return this._boundingBoxSize;
  63664. },
  63665. /**
  63666. * Gets or sets the size of the bounding box associated with the cube texture
  63667. * When defined, the cubemap will switch to local mode
  63668. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63669. * @example https://www.babylonjs-playground.com/#RNASML
  63670. */
  63671. set: function (value) {
  63672. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63673. return;
  63674. }
  63675. this._boundingBoxSize = value;
  63676. var scene = this.getScene();
  63677. if (scene) {
  63678. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63679. }
  63680. },
  63681. enumerable: true,
  63682. configurable: true
  63683. });
  63684. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63685. /**
  63686. * Gets texture matrix rotation angle around Y axis radians.
  63687. */
  63688. get: function () {
  63689. return this._rotationY;
  63690. },
  63691. /**
  63692. * Sets texture matrix rotation angle around Y axis in radians.
  63693. */
  63694. set: function (value) {
  63695. this._rotationY = value;
  63696. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63697. },
  63698. enumerable: true,
  63699. configurable: true
  63700. });
  63701. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63702. var rootUrlKey = "";
  63703. files.forEach(function (url) { return rootUrlKey += url; });
  63704. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63705. };
  63706. /**
  63707. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63708. * @param url defines the url of the prefiltered texture
  63709. * @param scene defines the scene the texture is attached to
  63710. * @param forcedExtension defines the extension of the file if different from the url
  63711. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63712. * @return the prefiltered texture
  63713. */
  63714. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63715. if (forcedExtension === void 0) { forcedExtension = null; }
  63716. if (createPolynomials === void 0) { createPolynomials = true; }
  63717. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63718. };
  63719. // Methods
  63720. CubeTexture.prototype.delayLoad = function () {
  63721. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63722. return;
  63723. }
  63724. var scene = this.getScene();
  63725. if (!scene) {
  63726. return;
  63727. }
  63728. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63729. this._texture = this._getFromCache(this.url, this._noMipmap);
  63730. if (!this._texture) {
  63731. if (this._prefiltered) {
  63732. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63733. }
  63734. else {
  63735. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63736. }
  63737. }
  63738. };
  63739. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63740. return this._textureMatrix;
  63741. };
  63742. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63743. this._textureMatrix = value;
  63744. };
  63745. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63746. var texture = BABYLON.SerializationHelper.Parse(function () {
  63747. var prefiltered = false;
  63748. if (parsedTexture.prefiltered) {
  63749. prefiltered = parsedTexture.prefiltered;
  63750. }
  63751. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63752. }, parsedTexture, scene);
  63753. // Local Cubemaps
  63754. if (parsedTexture.boundingBoxPosition) {
  63755. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63756. }
  63757. if (parsedTexture.boundingBoxSize) {
  63758. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63759. }
  63760. // Animations
  63761. if (parsedTexture.animations) {
  63762. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63763. var parsedAnimation = parsedTexture.animations[animationIndex];
  63764. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63765. }
  63766. }
  63767. return texture;
  63768. };
  63769. CubeTexture.prototype.clone = function () {
  63770. var _this = this;
  63771. return BABYLON.SerializationHelper.Clone(function () {
  63772. var scene = _this.getScene();
  63773. if (!scene) {
  63774. return _this;
  63775. }
  63776. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63777. }, this);
  63778. };
  63779. __decorate([
  63780. BABYLON.serialize("rotationY")
  63781. ], CubeTexture.prototype, "_rotationY", void 0);
  63782. return CubeTexture;
  63783. }(BABYLON.BaseTexture));
  63784. BABYLON.CubeTexture = CubeTexture;
  63785. })(BABYLON || (BABYLON = {}));
  63786. //# sourceMappingURL=babylon.cubeTexture.js.map
  63787. var BABYLON;
  63788. (function (BABYLON) {
  63789. /**
  63790. * Raw cube texture where the raw buffers are passed in
  63791. */
  63792. var RawCubeTexture = /** @class */ (function (_super) {
  63793. __extends(RawCubeTexture, _super);
  63794. /**
  63795. * Creates a cube texture where the raw buffers are passed in.
  63796. * @param scene defines the scene the texture is attached to
  63797. * @param data defines the array of data to use to create each face
  63798. * @param size defines the size of the textures
  63799. * @param format defines the format of the data
  63800. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63801. * @param generateMipMaps defines if the engine should generate the mip levels
  63802. * @param invertY defines if data must be stored with Y axis inverted
  63803. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63804. * @param compression defines the compression used (null by default)
  63805. */
  63806. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63807. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63808. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63809. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63810. if (invertY === void 0) { invertY = false; }
  63811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63812. if (compression === void 0) { compression = null; }
  63813. var _this = _super.call(this, "", scene) || this;
  63814. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63815. return _this;
  63816. }
  63817. /**
  63818. * Updates the raw cube texture.
  63819. * @param data defines the data to store
  63820. * @param format defines the data format
  63821. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63822. * @param invertY defines if data must be stored with Y axis inverted
  63823. * @param compression defines the compression used (null by default)
  63824. * @param level defines which level of the texture to update
  63825. */
  63826. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63827. if (compression === void 0) { compression = null; }
  63828. if (level === void 0) { level = 0; }
  63829. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63830. };
  63831. /**
  63832. * Updates a raw cube texture with RGBD encoded data.
  63833. * @param data defines the array of data [mipmap][face] to use to create each face
  63834. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63835. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63836. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63837. * @returns a promsie that resolves when the operation is complete
  63838. */
  63839. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63840. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63841. if (lodScale === void 0) { lodScale = 0.8; }
  63842. if (lodOffset === void 0) { lodOffset = 0; }
  63843. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63844. };
  63845. /**
  63846. * Clones the raw cube texture.
  63847. * @return a new cube texture
  63848. */
  63849. RawCubeTexture.prototype.clone = function () {
  63850. var _this = this;
  63851. return BABYLON.SerializationHelper.Clone(function () {
  63852. var scene = _this.getScene();
  63853. var internalTexture = _this._texture;
  63854. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63855. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63856. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63857. }
  63858. return texture;
  63859. }, this);
  63860. };
  63861. /** @hidden */
  63862. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63863. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63864. internalTexture._bufferViewArrayArray = data;
  63865. internalTexture._lodGenerationScale = lodScale;
  63866. internalTexture._lodGenerationOffset = lodOffset;
  63867. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63868. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63869. internalTexture.isReady = true;
  63870. });
  63871. };
  63872. return RawCubeTexture;
  63873. }(BABYLON.CubeTexture));
  63874. BABYLON.RawCubeTexture = RawCubeTexture;
  63875. })(BABYLON || (BABYLON = {}));
  63876. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63877. var BABYLON;
  63878. (function (BABYLON) {
  63879. var RenderTargetTexture = /** @class */ (function (_super) {
  63880. __extends(RenderTargetTexture, _super);
  63881. /**
  63882. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63883. * or used a shadow, depth texture...
  63884. * @param name The friendly name of the texture
  63885. * @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)
  63886. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63887. * @param generateMipMaps True if mip maps need to be generated after render.
  63888. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63889. * @param type The type of the buffer in the RTT (int, half float, float...)
  63890. * @param isCube True if a cube texture needs to be created
  63891. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63892. * @param generateDepthBuffer True to generate a depth buffer
  63893. * @param generateStencilBuffer True to generate a stencil buffer
  63894. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63895. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63896. */
  63897. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63898. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63899. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63900. if (isCube === void 0) { isCube = false; }
  63901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63902. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63903. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63904. if (isMulti === void 0) { isMulti = false; }
  63905. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63906. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63907. _this.isCube = isCube;
  63908. /**
  63909. * Use this list to define the list of mesh you want to render.
  63910. */
  63911. _this.renderList = new Array();
  63912. _this.renderParticles = true;
  63913. _this.renderSprites = false;
  63914. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63915. _this.ignoreCameraViewport = false;
  63916. // Events
  63917. /**
  63918. * An event triggered when the texture is unbind.
  63919. */
  63920. _this.onBeforeBindObservable = new BABYLON.Observable();
  63921. /**
  63922. * An event triggered when the texture is unbind.
  63923. */
  63924. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63925. /**
  63926. * An event triggered before rendering the texture
  63927. */
  63928. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63929. /**
  63930. * An event triggered after rendering the texture
  63931. */
  63932. _this.onAfterRenderObservable = new BABYLON.Observable();
  63933. /**
  63934. * An event triggered after the texture clear
  63935. */
  63936. _this.onClearObservable = new BABYLON.Observable();
  63937. _this._currentRefreshId = -1;
  63938. _this._refreshRate = 1;
  63939. _this._samples = 1;
  63940. /**
  63941. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63942. * It must define where the camera used to render the texture is set
  63943. */
  63944. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63945. scene = _this.getScene();
  63946. if (!scene) {
  63947. return _this;
  63948. }
  63949. _this._engine = scene.getEngine();
  63950. _this.name = name;
  63951. _this.isRenderTarget = true;
  63952. _this._initialSizeParameter = size;
  63953. _this._processSizeParameter(size);
  63954. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63955. });
  63956. _this._generateMipMaps = generateMipMaps ? true : false;
  63957. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63958. // Rendering groups
  63959. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63960. if (isMulti) {
  63961. return _this;
  63962. }
  63963. _this._renderTargetOptions = {
  63964. generateMipMaps: generateMipMaps,
  63965. type: type,
  63966. format: format,
  63967. samplingMode: samplingMode,
  63968. generateDepthBuffer: generateDepthBuffer,
  63969. generateStencilBuffer: generateStencilBuffer
  63970. };
  63971. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63972. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63973. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63974. }
  63975. if (isCube) {
  63976. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63977. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63978. _this._textureMatrix = BABYLON.Matrix.Identity();
  63979. }
  63980. else {
  63981. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63982. }
  63983. return _this;
  63984. }
  63985. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63986. get: function () {
  63987. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63988. },
  63989. enumerable: true,
  63990. configurable: true
  63991. });
  63992. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63993. get: function () {
  63994. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63995. },
  63996. enumerable: true,
  63997. configurable: true
  63998. });
  63999. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64000. get: function () {
  64001. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64002. },
  64003. enumerable: true,
  64004. configurable: true
  64005. });
  64006. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64007. set: function (callback) {
  64008. if (this._onAfterUnbindObserver) {
  64009. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64010. }
  64011. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64017. set: function (callback) {
  64018. if (this._onBeforeRenderObserver) {
  64019. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64020. }
  64021. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64022. },
  64023. enumerable: true,
  64024. configurable: true
  64025. });
  64026. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64027. set: function (callback) {
  64028. if (this._onAfterRenderObserver) {
  64029. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64030. }
  64031. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64032. },
  64033. enumerable: true,
  64034. configurable: true
  64035. });
  64036. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64037. set: function (callback) {
  64038. if (this._onClearObserver) {
  64039. this.onClearObservable.remove(this._onClearObserver);
  64040. }
  64041. this._onClearObserver = this.onClearObservable.add(callback);
  64042. },
  64043. enumerable: true,
  64044. configurable: true
  64045. });
  64046. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64047. get: function () {
  64048. return this._renderTargetOptions;
  64049. },
  64050. enumerable: true,
  64051. configurable: true
  64052. });
  64053. RenderTargetTexture.prototype._onRatioRescale = function () {
  64054. if (this._sizeRatio) {
  64055. this.resize(this._initialSizeParameter);
  64056. }
  64057. };
  64058. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64059. get: function () {
  64060. return this._boundingBoxSize;
  64061. },
  64062. /**
  64063. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64064. * When defined, the cubemap will switch to local mode
  64065. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64066. * @example https://www.babylonjs-playground.com/#RNASML
  64067. */
  64068. set: function (value) {
  64069. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64070. return;
  64071. }
  64072. this._boundingBoxSize = value;
  64073. var scene = this.getScene();
  64074. if (scene) {
  64075. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64076. }
  64077. },
  64078. enumerable: true,
  64079. configurable: true
  64080. });
  64081. /**
  64082. * Creates a depth stencil texture.
  64083. * This is only available in WebGL 2 or with the depth texture extension available.
  64084. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64085. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64086. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64087. */
  64088. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64089. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64090. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64091. if (generateStencil === void 0) { generateStencil = false; }
  64092. if (!this.getScene()) {
  64093. return;
  64094. }
  64095. var engine = this.getScene().getEngine();
  64096. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64097. bilinearFiltering: bilinearFiltering,
  64098. comparisonFunction: comparisonFunction,
  64099. generateStencil: generateStencil,
  64100. isCube: this.isCube
  64101. });
  64102. engine.setFrameBufferDepthStencilTexture(this);
  64103. };
  64104. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64105. if (size.ratio) {
  64106. this._sizeRatio = size.ratio;
  64107. this._size = {
  64108. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64109. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64110. };
  64111. }
  64112. else {
  64113. this._size = size;
  64114. }
  64115. };
  64116. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64117. get: function () {
  64118. return this._samples;
  64119. },
  64120. set: function (value) {
  64121. if (this._samples === value) {
  64122. return;
  64123. }
  64124. var scene = this.getScene();
  64125. if (!scene) {
  64126. return;
  64127. }
  64128. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64129. },
  64130. enumerable: true,
  64131. configurable: true
  64132. });
  64133. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64134. this._currentRefreshId = -1;
  64135. };
  64136. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64137. get: function () {
  64138. return this._refreshRate;
  64139. },
  64140. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64141. set: function (value) {
  64142. this._refreshRate = value;
  64143. this.resetRefreshCounter();
  64144. },
  64145. enumerable: true,
  64146. configurable: true
  64147. });
  64148. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64149. if (!this._postProcessManager) {
  64150. var scene = this.getScene();
  64151. if (!scene) {
  64152. return;
  64153. }
  64154. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64155. this._postProcesses = new Array();
  64156. }
  64157. this._postProcesses.push(postProcess);
  64158. this._postProcesses[0].autoClear = false;
  64159. };
  64160. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64161. if (!this._postProcesses) {
  64162. return;
  64163. }
  64164. if (dispose) {
  64165. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64166. var postProcess = _a[_i];
  64167. postProcess.dispose();
  64168. }
  64169. }
  64170. this._postProcesses = [];
  64171. };
  64172. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64173. if (!this._postProcesses) {
  64174. return;
  64175. }
  64176. var index = this._postProcesses.indexOf(postProcess);
  64177. if (index === -1) {
  64178. return;
  64179. }
  64180. this._postProcesses.splice(index, 1);
  64181. if (this._postProcesses.length > 0) {
  64182. this._postProcesses[0].autoClear = false;
  64183. }
  64184. };
  64185. RenderTargetTexture.prototype._shouldRender = function () {
  64186. if (this._currentRefreshId === -1) { // At least render once
  64187. this._currentRefreshId = 1;
  64188. return true;
  64189. }
  64190. if (this.refreshRate === this._currentRefreshId) {
  64191. this._currentRefreshId = 1;
  64192. return true;
  64193. }
  64194. this._currentRefreshId++;
  64195. return false;
  64196. };
  64197. RenderTargetTexture.prototype.getRenderSize = function () {
  64198. if (this._size.width) {
  64199. return this._size.width;
  64200. }
  64201. return this._size;
  64202. };
  64203. RenderTargetTexture.prototype.getRenderWidth = function () {
  64204. if (this._size.width) {
  64205. return this._size.width;
  64206. }
  64207. return this._size;
  64208. };
  64209. RenderTargetTexture.prototype.getRenderHeight = function () {
  64210. if (this._size.width) {
  64211. return this._size.height;
  64212. }
  64213. return this._size;
  64214. };
  64215. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64216. get: function () {
  64217. return true;
  64218. },
  64219. enumerable: true,
  64220. configurable: true
  64221. });
  64222. RenderTargetTexture.prototype.scale = function (ratio) {
  64223. var newSize = this.getRenderSize() * ratio;
  64224. this.resize(newSize);
  64225. };
  64226. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64227. if (this.isCube) {
  64228. return this._textureMatrix;
  64229. }
  64230. return _super.prototype.getReflectionTextureMatrix.call(this);
  64231. };
  64232. RenderTargetTexture.prototype.resize = function (size) {
  64233. this.releaseInternalTexture();
  64234. var scene = this.getScene();
  64235. if (!scene) {
  64236. return;
  64237. }
  64238. this._processSizeParameter(size);
  64239. if (this.isCube) {
  64240. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64241. }
  64242. else {
  64243. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64244. }
  64245. };
  64246. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64247. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64248. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64249. var scene = this.getScene();
  64250. if (!scene) {
  64251. return;
  64252. }
  64253. var engine = scene.getEngine();
  64254. if (this.useCameraPostProcesses !== undefined) {
  64255. useCameraPostProcess = this.useCameraPostProcesses;
  64256. }
  64257. if (this._waitingRenderList) {
  64258. this.renderList = [];
  64259. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64260. var id = this._waitingRenderList[index];
  64261. var mesh_1 = scene.getMeshByID(id);
  64262. if (mesh_1) {
  64263. this.renderList.push(mesh_1);
  64264. }
  64265. }
  64266. delete this._waitingRenderList;
  64267. }
  64268. // Is predicate defined?
  64269. if (this.renderListPredicate) {
  64270. if (this.renderList) {
  64271. this.renderList.splice(0); // Clear previous renderList
  64272. }
  64273. else {
  64274. this.renderList = [];
  64275. }
  64276. var scene = this.getScene();
  64277. if (!scene) {
  64278. return;
  64279. }
  64280. var sceneMeshes = scene.meshes;
  64281. for (var index = 0; index < sceneMeshes.length; index++) {
  64282. var mesh = sceneMeshes[index];
  64283. if (this.renderListPredicate(mesh)) {
  64284. this.renderList.push(mesh);
  64285. }
  64286. }
  64287. }
  64288. this.onBeforeBindObservable.notifyObservers(this);
  64289. // Set custom projection.
  64290. // Needs to be before binding to prevent changing the aspect ratio.
  64291. var camera;
  64292. if (this.activeCamera) {
  64293. camera = this.activeCamera;
  64294. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64295. if (this.activeCamera !== scene.activeCamera) {
  64296. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64297. }
  64298. }
  64299. else {
  64300. camera = scene.activeCamera;
  64301. if (camera) {
  64302. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64303. }
  64304. }
  64305. // Prepare renderingManager
  64306. this._renderingManager.reset();
  64307. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64308. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64309. var sceneRenderId = scene.getRenderId();
  64310. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64311. var mesh = currentRenderList[meshIndex];
  64312. if (mesh) {
  64313. if (!mesh.isReady(this.refreshRate === 0)) {
  64314. this.resetRefreshCounter();
  64315. continue;
  64316. }
  64317. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64318. var isMasked = void 0;
  64319. if (!this.renderList && camera) {
  64320. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64321. }
  64322. else {
  64323. isMasked = false;
  64324. }
  64325. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64326. mesh._activate(sceneRenderId);
  64327. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64328. var subMesh = mesh.subMeshes[subIndex];
  64329. scene._activeIndices.addCount(subMesh.indexCount, false);
  64330. this._renderingManager.dispatch(subMesh, mesh);
  64331. }
  64332. }
  64333. }
  64334. }
  64335. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64336. var particleSystem = scene.particleSystems[particleIndex];
  64337. var emitter = particleSystem.emitter;
  64338. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64339. continue;
  64340. }
  64341. if (currentRenderList.indexOf(emitter) >= 0) {
  64342. this._renderingManager.dispatchParticles(particleSystem);
  64343. }
  64344. }
  64345. if (this.isCube) {
  64346. for (var face = 0; face < 6; face++) {
  64347. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64348. scene.incrementRenderId();
  64349. scene.resetCachedMaterial();
  64350. }
  64351. }
  64352. else {
  64353. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64354. }
  64355. this.onAfterUnbindObservable.notifyObservers(this);
  64356. if (scene.activeCamera) {
  64357. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64358. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64359. }
  64360. engine.setViewport(scene.activeCamera.viewport);
  64361. }
  64362. scene.resetCachedMaterial();
  64363. };
  64364. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64365. var minimum = 128;
  64366. var x = renderDimension * scale;
  64367. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64368. // Ensure we don't exceed the render dimension (while staying POT)
  64369. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64370. };
  64371. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64372. var _this = this;
  64373. if (!this._texture) {
  64374. return;
  64375. }
  64376. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64377. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64378. });
  64379. };
  64380. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64381. var scene = this.getScene();
  64382. if (!scene) {
  64383. return;
  64384. }
  64385. var engine = scene.getEngine();
  64386. if (!this._texture) {
  64387. return;
  64388. }
  64389. // Bind
  64390. if (this._postProcessManager) {
  64391. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64392. }
  64393. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64394. if (this._texture) {
  64395. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64396. }
  64397. }
  64398. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64399. // Clear
  64400. if (this.onClearObservable.hasObservers()) {
  64401. this.onClearObservable.notifyObservers(engine);
  64402. }
  64403. else {
  64404. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64405. }
  64406. if (!this._doNotChangeAspectRatio) {
  64407. scene.updateTransformMatrix(true);
  64408. }
  64409. // Render
  64410. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64411. if (this._postProcessManager) {
  64412. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64413. }
  64414. else if (useCameraPostProcess) {
  64415. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64416. }
  64417. if (!this._doNotChangeAspectRatio) {
  64418. scene.updateTransformMatrix(true);
  64419. }
  64420. // Dump ?
  64421. if (dumpForDebug) {
  64422. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64423. }
  64424. // Unbind
  64425. if (!this.isCube || faceIndex === 5) {
  64426. if (this.isCube) {
  64427. if (faceIndex === 5) {
  64428. engine.generateMipMapsForCubemap(this._texture);
  64429. }
  64430. }
  64431. this.unbindFrameBuffer(engine, faceIndex);
  64432. }
  64433. else {
  64434. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64435. }
  64436. };
  64437. /**
  64438. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64439. * This allowed control for front to back rendering or reversly depending of the special needs.
  64440. *
  64441. * @param renderingGroupId The rendering group id corresponding to its index
  64442. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64443. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64444. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64445. */
  64446. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64447. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64448. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64449. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64450. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64451. };
  64452. /**
  64453. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64454. *
  64455. * @param renderingGroupId The rendering group id corresponding to its index
  64456. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64457. */
  64458. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64459. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64460. };
  64461. RenderTargetTexture.prototype.clone = function () {
  64462. var textureSize = this.getSize();
  64463. 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);
  64464. // Base texture
  64465. newTexture.hasAlpha = this.hasAlpha;
  64466. newTexture.level = this.level;
  64467. // RenderTarget Texture
  64468. newTexture.coordinatesMode = this.coordinatesMode;
  64469. if (this.renderList) {
  64470. newTexture.renderList = this.renderList.slice(0);
  64471. }
  64472. return newTexture;
  64473. };
  64474. RenderTargetTexture.prototype.serialize = function () {
  64475. if (!this.name) {
  64476. return null;
  64477. }
  64478. var serializationObject = _super.prototype.serialize.call(this);
  64479. serializationObject.renderTargetSize = this.getRenderSize();
  64480. serializationObject.renderList = [];
  64481. if (this.renderList) {
  64482. for (var index = 0; index < this.renderList.length; index++) {
  64483. serializationObject.renderList.push(this.renderList[index].id);
  64484. }
  64485. }
  64486. return serializationObject;
  64487. };
  64488. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64489. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64490. var objBuffer = this.getInternalTexture();
  64491. var scene = this.getScene();
  64492. if (objBuffer && scene) {
  64493. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64494. }
  64495. };
  64496. RenderTargetTexture.prototype.dispose = function () {
  64497. if (this._postProcessManager) {
  64498. this._postProcessManager.dispose();
  64499. this._postProcessManager = null;
  64500. }
  64501. this.clearPostProcesses(true);
  64502. if (this._resizeObserver) {
  64503. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64504. this._resizeObserver = null;
  64505. }
  64506. this.renderList = null;
  64507. // Remove from custom render targets
  64508. var scene = this.getScene();
  64509. if (!scene) {
  64510. return;
  64511. }
  64512. var index = scene.customRenderTargets.indexOf(this);
  64513. if (index >= 0) {
  64514. scene.customRenderTargets.splice(index, 1);
  64515. }
  64516. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64517. var camera = _a[_i];
  64518. index = camera.customRenderTargets.indexOf(this);
  64519. if (index >= 0) {
  64520. camera.customRenderTargets.splice(index, 1);
  64521. }
  64522. }
  64523. _super.prototype.dispose.call(this);
  64524. };
  64525. RenderTargetTexture.prototype._rebuild = function () {
  64526. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64527. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64528. }
  64529. if (this._postProcessManager) {
  64530. this._postProcessManager._rebuild();
  64531. }
  64532. };
  64533. /**
  64534. * Clear the info related to rendering groups preventing retention point in material dispose.
  64535. */
  64536. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64537. if (this._renderingManager) {
  64538. this._renderingManager.freeRenderingGroups();
  64539. }
  64540. };
  64541. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64542. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64543. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64544. return RenderTargetTexture;
  64545. }(BABYLON.Texture));
  64546. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64547. })(BABYLON || (BABYLON = {}));
  64548. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64549. var BABYLON;
  64550. (function (BABYLON) {
  64551. ;
  64552. var MultiRenderTarget = /** @class */ (function (_super) {
  64553. __extends(MultiRenderTarget, _super);
  64554. function MultiRenderTarget(name, size, count, scene, options) {
  64555. var _this = this;
  64556. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64557. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64558. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64559. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64560. _this._engine = scene.getEngine();
  64561. if (!_this.isSupported) {
  64562. _this.dispose();
  64563. return;
  64564. }
  64565. var types = [];
  64566. var samplingModes = [];
  64567. for (var i = 0; i < count; i++) {
  64568. if (options && options.types && options.types[i] !== undefined) {
  64569. types.push(options.types[i]);
  64570. }
  64571. else {
  64572. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64573. }
  64574. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64575. samplingModes.push(options.samplingModes[i]);
  64576. }
  64577. else {
  64578. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64579. }
  64580. }
  64581. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64582. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64583. _this._size = size;
  64584. _this._multiRenderTargetOptions = {
  64585. samplingModes: samplingModes,
  64586. generateMipMaps: generateMipMaps,
  64587. generateDepthBuffer: generateDepthBuffer,
  64588. generateStencilBuffer: generateStencilBuffer,
  64589. generateDepthTexture: generateDepthTexture,
  64590. types: types,
  64591. textureCount: count
  64592. };
  64593. _this._createInternalTextures();
  64594. _this._createTextures();
  64595. return _this;
  64596. }
  64597. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64598. get: function () {
  64599. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64600. },
  64601. enumerable: true,
  64602. configurable: true
  64603. });
  64604. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64605. get: function () {
  64606. return this._textures;
  64607. },
  64608. enumerable: true,
  64609. configurable: true
  64610. });
  64611. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64612. get: function () {
  64613. return this._textures[this._textures.length - 1];
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64619. set: function (wrap) {
  64620. if (this._textures) {
  64621. for (var i = 0; i < this._textures.length; i++) {
  64622. this._textures[i].wrapU = wrap;
  64623. }
  64624. }
  64625. },
  64626. enumerable: true,
  64627. configurable: true
  64628. });
  64629. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64630. set: function (wrap) {
  64631. if (this._textures) {
  64632. for (var i = 0; i < this._textures.length; i++) {
  64633. this._textures[i].wrapV = wrap;
  64634. }
  64635. }
  64636. },
  64637. enumerable: true,
  64638. configurable: true
  64639. });
  64640. MultiRenderTarget.prototype._rebuild = function () {
  64641. this.releaseInternalTextures();
  64642. this._createInternalTextures();
  64643. for (var i = 0; i < this._internalTextures.length; i++) {
  64644. var texture = this._textures[i];
  64645. texture._texture = this._internalTextures[i];
  64646. }
  64647. // Keeps references to frame buffer and stencil/depth buffer
  64648. this._texture = this._internalTextures[0];
  64649. };
  64650. MultiRenderTarget.prototype._createInternalTextures = function () {
  64651. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64652. };
  64653. MultiRenderTarget.prototype._createTextures = function () {
  64654. this._textures = [];
  64655. for (var i = 0; i < this._internalTextures.length; i++) {
  64656. var texture = new BABYLON.Texture(null, this.getScene());
  64657. texture._texture = this._internalTextures[i];
  64658. this._textures.push(texture);
  64659. }
  64660. // Keeps references to frame buffer and stencil/depth buffer
  64661. this._texture = this._internalTextures[0];
  64662. };
  64663. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64664. get: function () {
  64665. return this._samples;
  64666. },
  64667. set: function (value) {
  64668. if (this._samples === value) {
  64669. return;
  64670. }
  64671. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64672. },
  64673. enumerable: true,
  64674. configurable: true
  64675. });
  64676. MultiRenderTarget.prototype.resize = function (size) {
  64677. this.releaseInternalTextures();
  64678. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64679. this._createInternalTextures();
  64680. };
  64681. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64682. var _this = this;
  64683. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64684. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64685. });
  64686. };
  64687. MultiRenderTarget.prototype.dispose = function () {
  64688. this.releaseInternalTextures();
  64689. _super.prototype.dispose.call(this);
  64690. };
  64691. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64692. if (!this._internalTextures) {
  64693. return;
  64694. }
  64695. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64696. if (this._internalTextures[i] !== undefined) {
  64697. this._internalTextures[i].dispose();
  64698. this._internalTextures.splice(i, 1);
  64699. }
  64700. }
  64701. };
  64702. return MultiRenderTarget;
  64703. }(BABYLON.RenderTargetTexture));
  64704. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64705. })(BABYLON || (BABYLON = {}));
  64706. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64707. var BABYLON;
  64708. (function (BABYLON) {
  64709. var MirrorTexture = /** @class */ (function (_super) {
  64710. __extends(MirrorTexture, _super);
  64711. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64712. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64714. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64715. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64716. _this.scene = scene;
  64717. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64718. _this._transformMatrix = BABYLON.Matrix.Zero();
  64719. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64720. _this._adaptiveBlurKernel = 0;
  64721. _this._blurKernelX = 0;
  64722. _this._blurKernelY = 0;
  64723. _this._blurRatio = 1.0;
  64724. _this.ignoreCameraViewport = true;
  64725. _this._updateGammaSpace();
  64726. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64727. _this._updateGammaSpace;
  64728. });
  64729. _this.onBeforeRenderObservable.add(function () {
  64730. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64731. _this._savedViewMatrix = scene.getViewMatrix();
  64732. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64733. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64734. scene.clipPlane = _this.mirrorPlane;
  64735. scene.getEngine().cullBackFaces = false;
  64736. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64737. });
  64738. _this.onAfterRenderObservable.add(function () {
  64739. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64740. scene.getEngine().cullBackFaces = true;
  64741. scene._mirroredCameraPosition = null;
  64742. delete scene.clipPlane;
  64743. });
  64744. return _this;
  64745. }
  64746. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64747. get: function () {
  64748. return this._blurRatio;
  64749. },
  64750. set: function (value) {
  64751. if (this._blurRatio === value) {
  64752. return;
  64753. }
  64754. this._blurRatio = value;
  64755. this._preparePostProcesses();
  64756. },
  64757. enumerable: true,
  64758. configurable: true
  64759. });
  64760. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64761. set: function (value) {
  64762. this._adaptiveBlurKernel = value;
  64763. this._autoComputeBlurKernel();
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64769. set: function (value) {
  64770. this.blurKernelX = value;
  64771. this.blurKernelY = value;
  64772. },
  64773. enumerable: true,
  64774. configurable: true
  64775. });
  64776. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64777. get: function () {
  64778. return this._blurKernelX;
  64779. },
  64780. set: function (value) {
  64781. if (this._blurKernelX === value) {
  64782. return;
  64783. }
  64784. this._blurKernelX = value;
  64785. this._preparePostProcesses();
  64786. },
  64787. enumerable: true,
  64788. configurable: true
  64789. });
  64790. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64791. get: function () {
  64792. return this._blurKernelY;
  64793. },
  64794. set: function (value) {
  64795. if (this._blurKernelY === value) {
  64796. return;
  64797. }
  64798. this._blurKernelY = value;
  64799. this._preparePostProcesses();
  64800. },
  64801. enumerable: true,
  64802. configurable: true
  64803. });
  64804. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64805. var engine = this.getScene().getEngine();
  64806. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64807. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64808. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64809. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64810. };
  64811. MirrorTexture.prototype._onRatioRescale = function () {
  64812. if (this._sizeRatio) {
  64813. this.resize(this._initialSizeParameter);
  64814. if (!this._adaptiveBlurKernel) {
  64815. this._preparePostProcesses();
  64816. }
  64817. }
  64818. if (this._adaptiveBlurKernel) {
  64819. this._autoComputeBlurKernel();
  64820. }
  64821. };
  64822. MirrorTexture.prototype._updateGammaSpace = function () {
  64823. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64824. };
  64825. MirrorTexture.prototype._preparePostProcesses = function () {
  64826. this.clearPostProcesses(true);
  64827. if (this._blurKernelX && this._blurKernelY) {
  64828. var engine = this.getScene().getEngine();
  64829. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64830. 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);
  64831. this._blurX.autoClear = false;
  64832. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64833. this._blurX.inputTexture = this._texture;
  64834. }
  64835. else {
  64836. this._blurX.alwaysForcePOT = true;
  64837. }
  64838. 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);
  64839. this._blurY.autoClear = false;
  64840. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64841. this.addPostProcess(this._blurX);
  64842. this.addPostProcess(this._blurY);
  64843. }
  64844. else {
  64845. if (this._blurY) {
  64846. this.removePostProcess(this._blurY);
  64847. this._blurY.dispose();
  64848. this._blurY = null;
  64849. }
  64850. if (this._blurX) {
  64851. this.removePostProcess(this._blurX);
  64852. this._blurX.dispose();
  64853. this._blurX = null;
  64854. }
  64855. }
  64856. };
  64857. MirrorTexture.prototype.clone = function () {
  64858. var scene = this.getScene();
  64859. if (!scene) {
  64860. return this;
  64861. }
  64862. var textureSize = this.getSize();
  64863. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64864. // Base texture
  64865. newTexture.hasAlpha = this.hasAlpha;
  64866. newTexture.level = this.level;
  64867. // Mirror Texture
  64868. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64869. if (this.renderList) {
  64870. newTexture.renderList = this.renderList.slice(0);
  64871. }
  64872. return newTexture;
  64873. };
  64874. MirrorTexture.prototype.serialize = function () {
  64875. if (!this.name) {
  64876. return null;
  64877. }
  64878. var serializationObject = _super.prototype.serialize.call(this);
  64879. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64880. return serializationObject;
  64881. };
  64882. MirrorTexture.prototype.dispose = function () {
  64883. _super.prototype.dispose.call(this);
  64884. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64885. };
  64886. return MirrorTexture;
  64887. }(BABYLON.RenderTargetTexture));
  64888. BABYLON.MirrorTexture = MirrorTexture;
  64889. })(BABYLON || (BABYLON = {}));
  64890. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64891. var BABYLON;
  64892. (function (BABYLON) {
  64893. /**
  64894. * Creates a refraction texture used by refraction channel of the standard material.
  64895. * @param name the texture name
  64896. * @param size size of the underlying texture
  64897. * @param scene root scene
  64898. */
  64899. var RefractionTexture = /** @class */ (function (_super) {
  64900. __extends(RefractionTexture, _super);
  64901. function RefractionTexture(name, size, scene, generateMipMaps) {
  64902. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64903. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64904. _this.depth = 2.0;
  64905. _this.onBeforeRenderObservable.add(function () {
  64906. scene.clipPlane = _this.refractionPlane;
  64907. });
  64908. _this.onAfterRenderObservable.add(function () {
  64909. delete scene.clipPlane;
  64910. });
  64911. return _this;
  64912. }
  64913. RefractionTexture.prototype.clone = function () {
  64914. var scene = this.getScene();
  64915. if (!scene) {
  64916. return this;
  64917. }
  64918. var textureSize = this.getSize();
  64919. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64920. // Base texture
  64921. newTexture.hasAlpha = this.hasAlpha;
  64922. newTexture.level = this.level;
  64923. // Refraction Texture
  64924. newTexture.refractionPlane = this.refractionPlane.clone();
  64925. if (this.renderList) {
  64926. newTexture.renderList = this.renderList.slice(0);
  64927. }
  64928. newTexture.depth = this.depth;
  64929. return newTexture;
  64930. };
  64931. RefractionTexture.prototype.serialize = function () {
  64932. if (!this.name) {
  64933. return null;
  64934. }
  64935. var serializationObject = _super.prototype.serialize.call(this);
  64936. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64937. serializationObject.depth = this.depth;
  64938. return serializationObject;
  64939. };
  64940. return RefractionTexture;
  64941. }(BABYLON.RenderTargetTexture));
  64942. BABYLON.RefractionTexture = RefractionTexture;
  64943. })(BABYLON || (BABYLON = {}));
  64944. //# sourceMappingURL=babylon.refractionTexture.js.map
  64945. var BABYLON;
  64946. (function (BABYLON) {
  64947. /**
  64948. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64949. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64950. */
  64951. var DynamicTexture = /** @class */ (function (_super) {
  64952. __extends(DynamicTexture, _super);
  64953. /**
  64954. * Creates a {BABYLON.DynamicTexture}
  64955. * @param name defines the name of the texture
  64956. * @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
  64957. * @param scene defines the scene where you want the texture
  64958. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64959. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64960. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64961. */
  64962. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64963. if (scene === void 0) { scene = null; }
  64964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64965. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64966. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64967. _this.name = name;
  64968. _this._engine = _this.getScene().getEngine();
  64969. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64970. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64971. _this._generateMipMaps = generateMipMaps;
  64972. if (options.getContext) {
  64973. _this._canvas = options;
  64974. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64975. }
  64976. else {
  64977. _this._canvas = document.createElement("canvas");
  64978. if (options.width || options.width === 0) {
  64979. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64980. }
  64981. else {
  64982. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64983. }
  64984. }
  64985. var textureSize = _this.getSize();
  64986. _this._canvas.width = textureSize.width;
  64987. _this._canvas.height = textureSize.height;
  64988. _this._context = _this._canvas.getContext("2d");
  64989. return _this;
  64990. }
  64991. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64992. /**
  64993. * Gets the current state of canRescale
  64994. */
  64995. get: function () {
  64996. return true;
  64997. },
  64998. enumerable: true,
  64999. configurable: true
  65000. });
  65001. DynamicTexture.prototype._recreate = function (textureSize) {
  65002. this._canvas.width = textureSize.width;
  65003. this._canvas.height = textureSize.height;
  65004. this.releaseInternalTexture();
  65005. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65006. };
  65007. /**
  65008. * Scales the texture
  65009. * @param ratio the scale factor to apply to both width and height
  65010. */
  65011. DynamicTexture.prototype.scale = function (ratio) {
  65012. var textureSize = this.getSize();
  65013. textureSize.width *= ratio;
  65014. textureSize.height *= ratio;
  65015. this._recreate(textureSize);
  65016. };
  65017. /**
  65018. * Resizes the texture
  65019. * @param width the new width
  65020. * @param height the new height
  65021. */
  65022. DynamicTexture.prototype.scaleTo = function (width, height) {
  65023. var textureSize = this.getSize();
  65024. textureSize.width = width;
  65025. textureSize.height = height;
  65026. this._recreate(textureSize);
  65027. };
  65028. /**
  65029. * Gets the context of the canvas used by the texture
  65030. * @returns the canvas context of the dynamic texture
  65031. */
  65032. DynamicTexture.prototype.getContext = function () {
  65033. return this._context;
  65034. };
  65035. /**
  65036. * Clears the texture
  65037. */
  65038. DynamicTexture.prototype.clear = function () {
  65039. var size = this.getSize();
  65040. this._context.fillRect(0, 0, size.width, size.height);
  65041. };
  65042. /**
  65043. * Updates the texture
  65044. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65045. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65046. */
  65047. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65048. if (premulAlpha === void 0) { premulAlpha = false; }
  65049. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65050. };
  65051. /**
  65052. * Draws text onto the texture
  65053. * @param text defines the text to be drawn
  65054. * @param x defines the placement of the text from the left
  65055. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65056. * @param font defines the font to be used with font-style, font-size, font-name
  65057. * @param color defines the color used for the text
  65058. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65059. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65060. * @param update defines whether texture is immediately update (default is true)
  65061. */
  65062. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65063. if (update === void 0) { update = true; }
  65064. var size = this.getSize();
  65065. if (clearColor) {
  65066. this._context.fillStyle = clearColor;
  65067. this._context.fillRect(0, 0, size.width, size.height);
  65068. }
  65069. this._context.font = font;
  65070. if (x === null || x === undefined) {
  65071. var textSize = this._context.measureText(text);
  65072. x = (size.width - textSize.width) / 2;
  65073. }
  65074. if (y === null || y === undefined) {
  65075. var fontSize = parseInt((font.replace(/\D/g, '')));
  65076. y = (size.height / 2) + (fontSize / 3.65);
  65077. }
  65078. this._context.fillStyle = color;
  65079. this._context.fillText(text, x, y);
  65080. if (update) {
  65081. this.update(invertY);
  65082. }
  65083. };
  65084. /**
  65085. * Clones the texture
  65086. * @returns the clone of the texture.
  65087. */
  65088. DynamicTexture.prototype.clone = function () {
  65089. var scene = this.getScene();
  65090. if (!scene) {
  65091. return this;
  65092. }
  65093. var textureSize = this.getSize();
  65094. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65095. // Base texture
  65096. newTexture.hasAlpha = this.hasAlpha;
  65097. newTexture.level = this.level;
  65098. // Dynamic Texture
  65099. newTexture.wrapU = this.wrapU;
  65100. newTexture.wrapV = this.wrapV;
  65101. return newTexture;
  65102. };
  65103. /** @hidden */
  65104. DynamicTexture.prototype._rebuild = function () {
  65105. this.update();
  65106. };
  65107. return DynamicTexture;
  65108. }(BABYLON.Texture));
  65109. BABYLON.DynamicTexture = DynamicTexture;
  65110. })(BABYLON || (BABYLON = {}));
  65111. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65112. var BABYLON;
  65113. (function (BABYLON) {
  65114. var VideoTexture = /** @class */ (function (_super) {
  65115. __extends(VideoTexture, _super);
  65116. /**
  65117. * Creates a video texture.
  65118. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65119. * @param {string | null} name optional name, will detect from video source, if not defined
  65120. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65121. * @param {BABYLON.Scene} scene is obviously the current scene.
  65122. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65123. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65124. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65125. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65126. */
  65127. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65128. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65129. if (invertY === void 0) { invertY = false; }
  65130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65131. if (settings === void 0) { settings = {
  65132. autoPlay: true,
  65133. loop: true,
  65134. autoUpdateTexture: true,
  65135. }; }
  65136. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65137. _this._onUserActionRequestedObservable = null;
  65138. _this._stillImageCaptured = false;
  65139. _this._createInternalTexture = function () {
  65140. if (_this._texture != null) {
  65141. return;
  65142. }
  65143. if (!_this._engine.needPOTTextures ||
  65144. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65145. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65146. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65147. }
  65148. else {
  65149. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65150. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65151. _this._generateMipMaps = false;
  65152. }
  65153. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65154. if (!_this.video.autoplay) {
  65155. var oldHandler_1 = _this.video.onplaying;
  65156. var error_1 = false;
  65157. _this.video.onplaying = function () {
  65158. _this.video.onplaying = oldHandler_1;
  65159. _this._texture.isReady = true;
  65160. _this._updateInternalTexture();
  65161. if (!error_1) {
  65162. _this.video.pause();
  65163. }
  65164. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65165. _this.onLoadObservable.notifyObservers(_this);
  65166. }
  65167. };
  65168. var playing = _this.video.play();
  65169. if (playing) {
  65170. playing.then(function () {
  65171. // Everything is good.
  65172. })
  65173. .catch(function () {
  65174. error_1 = true;
  65175. // On Chrome for instance, new policies might prevent playing without user interaction.
  65176. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65177. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65178. }
  65179. });
  65180. }
  65181. else {
  65182. _this.video.onplaying = oldHandler_1;
  65183. _this._texture.isReady = true;
  65184. _this._updateInternalTexture();
  65185. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65186. _this.onLoadObservable.notifyObservers(_this);
  65187. }
  65188. }
  65189. }
  65190. else {
  65191. _this._texture.isReady = true;
  65192. _this._updateInternalTexture();
  65193. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65194. _this.onLoadObservable.notifyObservers(_this);
  65195. }
  65196. }
  65197. };
  65198. _this.reset = function () {
  65199. if (_this._texture == null) {
  65200. return;
  65201. }
  65202. _this._texture.dispose();
  65203. _this._texture = null;
  65204. };
  65205. _this._updateInternalTexture = function (e) {
  65206. if (_this._texture == null || !_this._texture.isReady) {
  65207. return;
  65208. }
  65209. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65210. return;
  65211. }
  65212. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65213. };
  65214. _this._engine = _this.getScene().getEngine();
  65215. _this._generateMipMaps = generateMipMaps;
  65216. _this._samplingMode = samplingMode;
  65217. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65218. _this.name = name || _this._getName(src);
  65219. _this.video = _this._getVideo(src);
  65220. if (settings.poster) {
  65221. _this.video.poster = settings.poster;
  65222. }
  65223. if (settings.autoPlay !== undefined) {
  65224. _this.video.autoplay = settings.autoPlay;
  65225. }
  65226. if (settings.loop !== undefined) {
  65227. _this.video.loop = settings.loop;
  65228. }
  65229. _this.video.setAttribute("playsinline", "");
  65230. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65231. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65232. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65233. _this.video.addEventListener("emptied", _this.reset);
  65234. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65235. _this._createInternalTexture();
  65236. }
  65237. return _this;
  65238. }
  65239. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65240. get: function () {
  65241. if (!this._onUserActionRequestedObservable) {
  65242. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65243. }
  65244. return this._onUserActionRequestedObservable;
  65245. },
  65246. enumerable: true,
  65247. configurable: true
  65248. });
  65249. VideoTexture.prototype._getName = function (src) {
  65250. if (src instanceof HTMLVideoElement) {
  65251. return src.currentSrc;
  65252. }
  65253. if (typeof src === "object") {
  65254. return src.toString();
  65255. }
  65256. return src;
  65257. };
  65258. ;
  65259. VideoTexture.prototype._getVideo = function (src) {
  65260. if (src instanceof HTMLVideoElement) {
  65261. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65262. return src;
  65263. }
  65264. var video = document.createElement("video");
  65265. if (typeof src === "string") {
  65266. BABYLON.Tools.SetCorsBehavior(src, video);
  65267. video.src = src;
  65268. }
  65269. else {
  65270. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65271. src.forEach(function (url) {
  65272. var source = document.createElement("source");
  65273. source.src = url;
  65274. video.appendChild(source);
  65275. });
  65276. }
  65277. return video;
  65278. };
  65279. ;
  65280. /**
  65281. * Internal method to initiate `update`.
  65282. */
  65283. VideoTexture.prototype._rebuild = function () {
  65284. this.update();
  65285. };
  65286. /**
  65287. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65288. */
  65289. VideoTexture.prototype.update = function () {
  65290. if (!this.autoUpdateTexture) {
  65291. // Expecting user to call `updateTexture` manually
  65292. return;
  65293. }
  65294. this.updateTexture(true);
  65295. };
  65296. /**
  65297. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65298. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65299. */
  65300. VideoTexture.prototype.updateTexture = function (isVisible) {
  65301. if (!isVisible) {
  65302. return;
  65303. }
  65304. if (this.video.paused && this._stillImageCaptured) {
  65305. return;
  65306. }
  65307. this._stillImageCaptured = true;
  65308. this._updateInternalTexture();
  65309. };
  65310. /**
  65311. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65312. * @param url New url.
  65313. */
  65314. VideoTexture.prototype.updateURL = function (url) {
  65315. this.video.src = url;
  65316. };
  65317. VideoTexture.prototype.dispose = function () {
  65318. _super.prototype.dispose.call(this);
  65319. if (this._onUserActionRequestedObservable) {
  65320. this._onUserActionRequestedObservable.clear();
  65321. this._onUserActionRequestedObservable = null;
  65322. }
  65323. this.video.removeEventListener("canplay", this._createInternalTexture);
  65324. this.video.removeEventListener("paused", this._updateInternalTexture);
  65325. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65326. this.video.removeEventListener("emptied", this.reset);
  65327. this.video.pause();
  65328. };
  65329. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65330. var video = document.createElement("video");
  65331. video.setAttribute('autoplay', '');
  65332. video.setAttribute('muted', '');
  65333. video.setAttribute('playsinline', '');
  65334. var constraintsDeviceId;
  65335. if (constraints && constraints.deviceId) {
  65336. constraintsDeviceId = {
  65337. exact: constraints.deviceId,
  65338. };
  65339. }
  65340. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65341. if (navigator.mediaDevices) {
  65342. navigator.mediaDevices.getUserMedia({ video: constraints })
  65343. .then(function (stream) {
  65344. if (video.mozSrcObject !== undefined) {
  65345. // hack for Firefox < 19
  65346. video.mozSrcObject = stream;
  65347. }
  65348. else {
  65349. video.srcObject = stream;
  65350. }
  65351. var onPlaying = function () {
  65352. if (onReady) {
  65353. onReady(new VideoTexture("video", video, scene, true, true));
  65354. }
  65355. video.removeEventListener("playing", onPlaying);
  65356. };
  65357. video.addEventListener("playing", onPlaying);
  65358. video.play();
  65359. })
  65360. .catch(function (err) {
  65361. BABYLON.Tools.Error(err.name);
  65362. });
  65363. }
  65364. else {
  65365. navigator.getUserMedia =
  65366. navigator.getUserMedia ||
  65367. navigator.webkitGetUserMedia ||
  65368. navigator.mozGetUserMedia ||
  65369. navigator.msGetUserMedia;
  65370. if (navigator.getUserMedia) {
  65371. navigator.getUserMedia({
  65372. video: {
  65373. deviceId: constraintsDeviceId,
  65374. width: {
  65375. min: (constraints && constraints.minWidth) || 256,
  65376. max: (constraints && constraints.maxWidth) || 640,
  65377. },
  65378. height: {
  65379. min: (constraints && constraints.minHeight) || 256,
  65380. max: (constraints && constraints.maxHeight) || 480,
  65381. },
  65382. },
  65383. }, function (stream) {
  65384. if (video.mozSrcObject !== undefined) {
  65385. // hack for Firefox < 19
  65386. video.mozSrcObject = stream;
  65387. }
  65388. else {
  65389. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65390. }
  65391. video.play();
  65392. if (onReady) {
  65393. onReady(new VideoTexture("video", video, scene, true, true));
  65394. }
  65395. }, function (e) {
  65396. BABYLON.Tools.Error(e.name);
  65397. });
  65398. }
  65399. }
  65400. };
  65401. return VideoTexture;
  65402. }(BABYLON.Texture));
  65403. BABYLON.VideoTexture = VideoTexture;
  65404. })(BABYLON || (BABYLON = {}));
  65405. //# sourceMappingURL=babylon.videoTexture.js.map
  65406. var BABYLON;
  65407. (function (BABYLON) {
  65408. var RawTexture = /** @class */ (function (_super) {
  65409. __extends(RawTexture, _super);
  65410. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65411. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65412. if (invertY === void 0) { invertY = false; }
  65413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65414. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65415. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65416. _this.format = format;
  65417. _this._engine = scene.getEngine();
  65418. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65419. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65420. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65421. return _this;
  65422. }
  65423. RawTexture.prototype.update = function (data) {
  65424. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65425. };
  65426. // Statics
  65427. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65428. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65429. if (invertY === void 0) { invertY = false; }
  65430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65431. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65432. };
  65433. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65434. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65435. if (invertY === void 0) { invertY = false; }
  65436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65437. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65438. };
  65439. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65440. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65441. if (invertY === void 0) { invertY = false; }
  65442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65443. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65444. };
  65445. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65446. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65447. if (invertY === void 0) { invertY = false; }
  65448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65449. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65450. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65451. };
  65452. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65453. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65454. if (invertY === void 0) { invertY = false; }
  65455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65456. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65457. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65458. };
  65459. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65460. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65461. if (invertY === void 0) { invertY = false; }
  65462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65463. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65464. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65465. };
  65466. return RawTexture;
  65467. }(BABYLON.Texture));
  65468. BABYLON.RawTexture = RawTexture;
  65469. })(BABYLON || (BABYLON = {}));
  65470. //# sourceMappingURL=babylon.rawTexture.js.map
  65471. var BABYLON;
  65472. (function (BABYLON) {
  65473. /**
  65474. * Class used to store 3D textures containing user data
  65475. */
  65476. var RawTexture3D = /** @class */ (function (_super) {
  65477. __extends(RawTexture3D, _super);
  65478. /**
  65479. * Create a new RawTexture3D
  65480. * @param data defines the data of the texture
  65481. * @param width defines the width of the texture
  65482. * @param height defines the height of the texture
  65483. * @param depth defines the depth of the texture
  65484. * @param format defines the texture format to use
  65485. * @param scene defines the hosting scene
  65486. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65487. * @param invertY defines if texture must be stored with Y axis inverted
  65488. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65489. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65490. */
  65491. function RawTexture3D(data, width, height, depth,
  65492. /** Gets or sets the texture format to use */
  65493. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65494. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65495. if (invertY === void 0) { invertY = false; }
  65496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65498. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65499. _this.format = format;
  65500. _this._engine = scene.getEngine();
  65501. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65502. _this.is3D = true;
  65503. return _this;
  65504. }
  65505. /**
  65506. * Update the texture with new data
  65507. * @param data defines the data to store in the texture
  65508. */
  65509. RawTexture3D.prototype.update = function (data) {
  65510. if (!this._texture) {
  65511. return;
  65512. }
  65513. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65514. };
  65515. return RawTexture3D;
  65516. }(BABYLON.Texture));
  65517. BABYLON.RawTexture3D = RawTexture3D;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. /**
  65523. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65524. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65525. */
  65526. var PostProcessManager = /** @class */ (function () {
  65527. /**
  65528. * Creates a new instance PostProcess
  65529. * @param scene The scene that the post process is associated with.
  65530. */
  65531. function PostProcessManager(scene) {
  65532. this._vertexBuffers = {};
  65533. this._scene = scene;
  65534. }
  65535. PostProcessManager.prototype._prepareBuffers = function () {
  65536. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65537. return;
  65538. }
  65539. // VBO
  65540. var vertices = [];
  65541. vertices.push(1, 1);
  65542. vertices.push(-1, 1);
  65543. vertices.push(-1, -1);
  65544. vertices.push(1, -1);
  65545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65546. this._buildIndexBuffer();
  65547. };
  65548. PostProcessManager.prototype._buildIndexBuffer = function () {
  65549. // Indices
  65550. var indices = [];
  65551. indices.push(0);
  65552. indices.push(1);
  65553. indices.push(2);
  65554. indices.push(0);
  65555. indices.push(2);
  65556. indices.push(3);
  65557. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65558. };
  65559. /**
  65560. * Rebuilds the vertex buffers of the manager.
  65561. */
  65562. PostProcessManager.prototype._rebuild = function () {
  65563. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65564. if (!vb) {
  65565. return;
  65566. }
  65567. vb._rebuild();
  65568. this._buildIndexBuffer();
  65569. };
  65570. // Methods
  65571. /**
  65572. * Prepares a frame to be run through a post process.
  65573. * @param sourceTexture The input texture to the post procesess. (default: null)
  65574. * @param postProcesses An array of post processes to be run. (default: null)
  65575. * @returns True if the post processes were able to be run.
  65576. */
  65577. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65578. if (sourceTexture === void 0) { sourceTexture = null; }
  65579. if (postProcesses === void 0) { postProcesses = null; }
  65580. var camera = this._scene.activeCamera;
  65581. if (!camera) {
  65582. return false;
  65583. }
  65584. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65585. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65586. return false;
  65587. }
  65588. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65589. return true;
  65590. };
  65591. /**
  65592. * Manually render a set of post processes to a texture.
  65593. * @param postProcesses An array of post processes to be run.
  65594. * @param targetTexture The target texture to render to.
  65595. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65596. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65597. * @param lodLevel defines which lod of the texture to render to
  65598. */
  65599. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65600. if (targetTexture === void 0) { targetTexture = null; }
  65601. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65602. if (faceIndex === void 0) { faceIndex = 0; }
  65603. if (lodLevel === void 0) { lodLevel = 0; }
  65604. var engine = this._scene.getEngine();
  65605. for (var index = 0; index < postProcesses.length; index++) {
  65606. if (index < postProcesses.length - 1) {
  65607. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65608. }
  65609. else {
  65610. if (targetTexture) {
  65611. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65612. }
  65613. else {
  65614. engine.restoreDefaultFramebuffer();
  65615. }
  65616. }
  65617. var pp = postProcesses[index];
  65618. var effect = pp.apply();
  65619. if (effect) {
  65620. pp.onBeforeRenderObservable.notifyObservers(effect);
  65621. // VBOs
  65622. this._prepareBuffers();
  65623. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65624. // Draw order
  65625. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65626. pp.onAfterRenderObservable.notifyObservers(effect);
  65627. }
  65628. }
  65629. // Restore depth buffer
  65630. engine.setDepthBuffer(true);
  65631. engine.setDepthWrite(true);
  65632. };
  65633. /**
  65634. * Finalize the result of the output of the postprocesses.
  65635. * @param doNotPresent If true the result will not be displayed to the screen.
  65636. * @param targetTexture The target texture to render to.
  65637. * @param faceIndex The index of the face to bind the target texture to.
  65638. * @param postProcesses The array of post processes to render.
  65639. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65640. */
  65641. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65642. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65643. var camera = this._scene.activeCamera;
  65644. if (!camera) {
  65645. return;
  65646. }
  65647. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65648. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65649. return;
  65650. }
  65651. var engine = this._scene.getEngine();
  65652. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65653. var pp = postProcesses[index];
  65654. if (index < len - 1) {
  65655. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65656. }
  65657. else {
  65658. if (targetTexture) {
  65659. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65660. pp._outputTexture = targetTexture;
  65661. }
  65662. else {
  65663. engine.restoreDefaultFramebuffer();
  65664. pp._outputTexture = null;
  65665. }
  65666. }
  65667. if (doNotPresent) {
  65668. break;
  65669. }
  65670. var effect = pp.apply();
  65671. if (effect) {
  65672. pp.onBeforeRenderObservable.notifyObservers(effect);
  65673. // VBOs
  65674. this._prepareBuffers();
  65675. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65676. // Draw order
  65677. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65678. pp.onAfterRenderObservable.notifyObservers(effect);
  65679. }
  65680. }
  65681. // Restore states
  65682. engine.setDepthBuffer(true);
  65683. engine.setDepthWrite(true);
  65684. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65685. };
  65686. /**
  65687. * Disposes of the post process manager.
  65688. */
  65689. PostProcessManager.prototype.dispose = function () {
  65690. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65691. if (buffer) {
  65692. buffer.dispose();
  65693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65694. }
  65695. if (this._indexBuffer) {
  65696. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65697. this._indexBuffer = null;
  65698. }
  65699. };
  65700. return PostProcessManager;
  65701. }());
  65702. BABYLON.PostProcessManager = PostProcessManager;
  65703. })(BABYLON || (BABYLON = {}));
  65704. //# sourceMappingURL=babylon.postProcessManager.js.map
  65705. var BABYLON;
  65706. (function (BABYLON) {
  65707. /**
  65708. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65709. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65710. */
  65711. var PostProcess = /** @class */ (function () {
  65712. /**
  65713. * Creates a new instance PostProcess
  65714. * @param name The name of the PostProcess.
  65715. * @param fragmentUrl The url of the fragment shader to be used.
  65716. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65717. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65718. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65719. * @param camera The camera to apply the render pass to.
  65720. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65721. * @param engine The engine which the post process will be applied. (default: current engine)
  65722. * @param reusable If the post process can be reused on the same frame. (default: false)
  65723. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65724. * @param textureType Type of textures used when performing the post process. (default: 0)
  65725. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65726. * @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
  65727. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65728. */
  65729. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65731. if (defines === void 0) { defines = null; }
  65732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65733. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65734. if (blockCompilation === void 0) { blockCompilation = false; }
  65735. this.name = name;
  65736. /**
  65737. * Width of the texture to apply the post process on
  65738. */
  65739. this.width = -1;
  65740. /**
  65741. * Height of the texture to apply the post process on
  65742. */
  65743. this.height = -1;
  65744. /**
  65745. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65746. */
  65747. this._outputTexture = null;
  65748. /**
  65749. * If the buffer needs to be cleared before applying the post process. (default: true)
  65750. * Should be set to false if shader will overwrite all previous pixels.
  65751. */
  65752. this.autoClear = true;
  65753. /**
  65754. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65755. */
  65756. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65757. /**
  65758. * Animations to be used for the post processing
  65759. */
  65760. this.animations = new Array();
  65761. /**
  65762. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65763. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65764. */
  65765. this.enablePixelPerfectMode = false;
  65766. /**
  65767. * Force the postprocess to be applied without taking in account viewport
  65768. */
  65769. this.forceFullscreenViewport = true;
  65770. /**
  65771. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65772. *
  65773. * | Value | Type | Description |
  65774. * | ----- | ----------------------------------- | ----------- |
  65775. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65776. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65777. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65778. *
  65779. */
  65780. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65781. /**
  65782. * Force textures to be a power of two (default: false)
  65783. */
  65784. this.alwaysForcePOT = false;
  65785. /**
  65786. * Number of sample textures (default: 1)
  65787. */
  65788. this.samples = 1;
  65789. /**
  65790. * Modify the scale of the post process to be the same as the viewport (default: false)
  65791. */
  65792. this.adaptScaleToCurrentViewport = false;
  65793. this._reusable = false;
  65794. /**
  65795. * Smart array of input and output textures for the post process.
  65796. */
  65797. this._textures = new BABYLON.SmartArray(2);
  65798. /**
  65799. * The index in _textures that corresponds to the output texture.
  65800. */
  65801. this._currentRenderTextureInd = 0;
  65802. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65803. this._texelSize = BABYLON.Vector2.Zero();
  65804. // Events
  65805. /**
  65806. * An event triggered when the postprocess is activated.
  65807. */
  65808. this.onActivateObservable = new BABYLON.Observable();
  65809. /**
  65810. * An event triggered when the postprocess changes its size.
  65811. */
  65812. this.onSizeChangedObservable = new BABYLON.Observable();
  65813. /**
  65814. * An event triggered when the postprocess applies its effect.
  65815. */
  65816. this.onApplyObservable = new BABYLON.Observable();
  65817. /**
  65818. * An event triggered before rendering the postprocess
  65819. */
  65820. this.onBeforeRenderObservable = new BABYLON.Observable();
  65821. /**
  65822. * An event triggered after rendering the postprocess
  65823. */
  65824. this.onAfterRenderObservable = new BABYLON.Observable();
  65825. if (camera != null) {
  65826. this._camera = camera;
  65827. this._scene = camera.getScene();
  65828. camera.attachPostProcess(this);
  65829. this._engine = this._scene.getEngine();
  65830. this._scene.postProcesses.push(this);
  65831. }
  65832. else if (engine) {
  65833. this._engine = engine;
  65834. this._engine.postProcesses.push(this);
  65835. }
  65836. this._options = options;
  65837. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65838. this._reusable = reusable || false;
  65839. this._textureType = textureType;
  65840. this._samplers = samplers || [];
  65841. this._samplers.push("textureSampler");
  65842. this._fragmentUrl = fragmentUrl;
  65843. this._vertexUrl = vertexUrl;
  65844. this._parameters = parameters || [];
  65845. this._parameters.push("scale");
  65846. this._indexParameters = indexParameters;
  65847. if (!blockCompilation) {
  65848. this.updateEffect(defines);
  65849. }
  65850. }
  65851. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65852. /**
  65853. * A function that is added to the onActivateObservable
  65854. */
  65855. set: function (callback) {
  65856. if (this._onActivateObserver) {
  65857. this.onActivateObservable.remove(this._onActivateObserver);
  65858. }
  65859. if (callback) {
  65860. this._onActivateObserver = this.onActivateObservable.add(callback);
  65861. }
  65862. },
  65863. enumerable: true,
  65864. configurable: true
  65865. });
  65866. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65867. /**
  65868. * A function that is added to the onSizeChangedObservable
  65869. */
  65870. set: function (callback) {
  65871. if (this._onSizeChangedObserver) {
  65872. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65873. }
  65874. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65875. },
  65876. enumerable: true,
  65877. configurable: true
  65878. });
  65879. Object.defineProperty(PostProcess.prototype, "onApply", {
  65880. /**
  65881. * A function that is added to the onApplyObservable
  65882. */
  65883. set: function (callback) {
  65884. if (this._onApplyObserver) {
  65885. this.onApplyObservable.remove(this._onApplyObserver);
  65886. }
  65887. this._onApplyObserver = this.onApplyObservable.add(callback);
  65888. },
  65889. enumerable: true,
  65890. configurable: true
  65891. });
  65892. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65893. /**
  65894. * A function that is added to the onBeforeRenderObservable
  65895. */
  65896. set: function (callback) {
  65897. if (this._onBeforeRenderObserver) {
  65898. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65899. }
  65900. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65901. },
  65902. enumerable: true,
  65903. configurable: true
  65904. });
  65905. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65906. /**
  65907. * A function that is added to the onAfterRenderObservable
  65908. */
  65909. set: function (callback) {
  65910. if (this._onAfterRenderObserver) {
  65911. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65912. }
  65913. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65914. },
  65915. enumerable: true,
  65916. configurable: true
  65917. });
  65918. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65919. /**
  65920. * 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
  65921. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65922. */
  65923. get: function () {
  65924. return this._textures.data[this._currentRenderTextureInd];
  65925. },
  65926. set: function (value) {
  65927. this._forcedOutputTexture = value;
  65928. },
  65929. enumerable: true,
  65930. configurable: true
  65931. });
  65932. /**
  65933. * Gets the camera which post process is applied to.
  65934. * @returns The camera the post process is applied to.
  65935. */
  65936. PostProcess.prototype.getCamera = function () {
  65937. return this._camera;
  65938. };
  65939. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65940. /**
  65941. * Gets the texel size of the postprocess.
  65942. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65943. */
  65944. get: function () {
  65945. if (this._shareOutputWithPostProcess) {
  65946. return this._shareOutputWithPostProcess.texelSize;
  65947. }
  65948. if (this._forcedOutputTexture) {
  65949. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65950. }
  65951. return this._texelSize;
  65952. },
  65953. enumerable: true,
  65954. configurable: true
  65955. });
  65956. /**
  65957. * Gets the engine which this post process belongs to.
  65958. * @returns The engine the post process was enabled with.
  65959. */
  65960. PostProcess.prototype.getEngine = function () {
  65961. return this._engine;
  65962. };
  65963. /**
  65964. * The effect that is created when initializing the post process.
  65965. * @returns The created effect corrisponding the the postprocess.
  65966. */
  65967. PostProcess.prototype.getEffect = function () {
  65968. return this._effect;
  65969. };
  65970. /**
  65971. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65972. * @param postProcess The post process to share the output with.
  65973. * @returns This post process.
  65974. */
  65975. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65976. this._disposeTextures();
  65977. this._shareOutputWithPostProcess = postProcess;
  65978. return this;
  65979. };
  65980. /**
  65981. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65982. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65983. */
  65984. PostProcess.prototype.useOwnOutput = function () {
  65985. if (this._textures.length == 0) {
  65986. this._textures = new BABYLON.SmartArray(2);
  65987. }
  65988. this._shareOutputWithPostProcess = null;
  65989. };
  65990. /**
  65991. * Updates the effect with the current post process compile time values and recompiles the shader.
  65992. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65993. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65994. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65995. * @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
  65996. * @param onCompiled Called when the shader has been compiled.
  65997. * @param onError Called if there is an error when compiling a shader.
  65998. */
  65999. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  66000. if (defines === void 0) { defines = null; }
  66001. if (uniforms === void 0) { uniforms = null; }
  66002. if (samplers === void 0) { samplers = null; }
  66003. 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);
  66004. };
  66005. /**
  66006. * The post process is reusable if it can be used multiple times within one frame.
  66007. * @returns If the post process is reusable
  66008. */
  66009. PostProcess.prototype.isReusable = function () {
  66010. return this._reusable;
  66011. };
  66012. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  66013. PostProcess.prototype.markTextureDirty = function () {
  66014. this.width = -1;
  66015. };
  66016. /**
  66017. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  66018. * 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.
  66019. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  66020. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  66021. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  66022. * @returns The target texture that was bound to be written to.
  66023. */
  66024. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  66025. var _this = this;
  66026. if (sourceTexture === void 0) { sourceTexture = null; }
  66027. camera = camera || this._camera;
  66028. var scene = camera.getScene();
  66029. var engine = scene.getEngine();
  66030. var maxSize = engine.getCaps().maxTextureSize;
  66031. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  66032. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  66033. // 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
  66034. var webVRCamera = camera.parent;
  66035. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  66036. requiredWidth /= 2;
  66037. }
  66038. var desiredWidth = (this._options.width || requiredWidth);
  66039. var desiredHeight = this._options.height || requiredHeight;
  66040. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  66041. if (this.adaptScaleToCurrentViewport) {
  66042. var currentViewport = engine.currentViewport;
  66043. if (currentViewport) {
  66044. desiredWidth *= currentViewport.width;
  66045. desiredHeight *= currentViewport.height;
  66046. }
  66047. }
  66048. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  66049. if (!this._options.width) {
  66050. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  66051. }
  66052. if (!this._options.height) {
  66053. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  66054. }
  66055. }
  66056. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  66057. if (this._textures.length > 0) {
  66058. for (var i = 0; i < this._textures.length; i++) {
  66059. this._engine._releaseTexture(this._textures.data[i]);
  66060. }
  66061. this._textures.reset();
  66062. }
  66063. this.width = desiredWidth;
  66064. this.height = desiredHeight;
  66065. var textureSize = { width: this.width, height: this.height };
  66066. var textureOptions = {
  66067. generateMipMaps: false,
  66068. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  66069. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  66070. samplingMode: this.renderTargetSamplingMode,
  66071. type: this._textureType
  66072. };
  66073. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66074. if (this._reusable) {
  66075. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66076. }
  66077. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  66078. this.onSizeChangedObservable.notifyObservers(this);
  66079. }
  66080. this._textures.forEach(function (texture) {
  66081. if (texture.samples !== _this.samples) {
  66082. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  66083. }
  66084. });
  66085. }
  66086. var target;
  66087. if (this._shareOutputWithPostProcess) {
  66088. target = this._shareOutputWithPostProcess.inputTexture;
  66089. }
  66090. else if (this._forcedOutputTexture) {
  66091. target = this._forcedOutputTexture;
  66092. this.width = this._forcedOutputTexture.width;
  66093. this.height = this._forcedOutputTexture.height;
  66094. }
  66095. else {
  66096. target = this.inputTexture;
  66097. }
  66098. // Bind the input of this post process to be used as the output of the previous post process.
  66099. if (this.enablePixelPerfectMode) {
  66100. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66101. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66102. }
  66103. else {
  66104. this._scaleRatio.copyFromFloats(1, 1);
  66105. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66106. }
  66107. this.onActivateObservable.notifyObservers(camera);
  66108. // Clear
  66109. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66110. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66111. }
  66112. if (this._reusable) {
  66113. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66114. }
  66115. return target;
  66116. };
  66117. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66118. /**
  66119. * If the post process is supported.
  66120. */
  66121. get: function () {
  66122. return this._effect.isSupported;
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66128. /**
  66129. * The aspect ratio of the output texture.
  66130. */
  66131. get: function () {
  66132. if (this._shareOutputWithPostProcess) {
  66133. return this._shareOutputWithPostProcess.aspectRatio;
  66134. }
  66135. if (this._forcedOutputTexture) {
  66136. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66137. }
  66138. return this.width / this.height;
  66139. },
  66140. enumerable: true,
  66141. configurable: true
  66142. });
  66143. /**
  66144. * Get a value indicating if the post-process is ready to be used
  66145. * @returns true if the post-process is ready (shader is compiled)
  66146. */
  66147. PostProcess.prototype.isReady = function () {
  66148. return this._effect && this._effect.isReady();
  66149. };
  66150. /**
  66151. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66152. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66153. */
  66154. PostProcess.prototype.apply = function () {
  66155. // Check
  66156. if (!this._effect || !this._effect.isReady())
  66157. return null;
  66158. // States
  66159. this._engine.enableEffect(this._effect);
  66160. this._engine.setState(false);
  66161. this._engine.setDepthBuffer(false);
  66162. this._engine.setDepthWrite(false);
  66163. // Alpha
  66164. this._engine.setAlphaMode(this.alphaMode);
  66165. if (this.alphaConstants) {
  66166. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66167. }
  66168. // Bind the output texture of the preivous post process as the input to this post process.
  66169. var source;
  66170. if (this._shareOutputWithPostProcess) {
  66171. source = this._shareOutputWithPostProcess.inputTexture;
  66172. }
  66173. else if (this._forcedOutputTexture) {
  66174. source = this._forcedOutputTexture;
  66175. }
  66176. else {
  66177. source = this.inputTexture;
  66178. }
  66179. this._effect._bindTexture("textureSampler", source);
  66180. // Parameters
  66181. this._effect.setVector2("scale", this._scaleRatio);
  66182. this.onApplyObservable.notifyObservers(this._effect);
  66183. return this._effect;
  66184. };
  66185. PostProcess.prototype._disposeTextures = function () {
  66186. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66187. return;
  66188. }
  66189. if (this._textures.length > 0) {
  66190. for (var i = 0; i < this._textures.length; i++) {
  66191. this._engine._releaseTexture(this._textures.data[i]);
  66192. }
  66193. }
  66194. this._textures.dispose();
  66195. };
  66196. /**
  66197. * Disposes the post process.
  66198. * @param camera The camera to dispose the post process on.
  66199. */
  66200. PostProcess.prototype.dispose = function (camera) {
  66201. camera = camera || this._camera;
  66202. this._disposeTextures();
  66203. if (this._scene) {
  66204. var index_1 = this._scene.postProcesses.indexOf(this);
  66205. if (index_1 !== -1) {
  66206. this._scene.postProcesses.splice(index_1, 1);
  66207. }
  66208. }
  66209. else {
  66210. var index_2 = this._engine.postProcesses.indexOf(this);
  66211. if (index_2 !== -1) {
  66212. this._engine.postProcesses.splice(index_2, 1);
  66213. }
  66214. }
  66215. if (!camera) {
  66216. return;
  66217. }
  66218. camera.detachPostProcess(this);
  66219. var index = camera._postProcesses.indexOf(this);
  66220. if (index === 0 && camera._postProcesses.length > 0) {
  66221. var firstPostProcess = this._camera._getFirstPostProcess();
  66222. if (firstPostProcess) {
  66223. firstPostProcess.markTextureDirty();
  66224. }
  66225. }
  66226. this.onActivateObservable.clear();
  66227. this.onAfterRenderObservable.clear();
  66228. this.onApplyObservable.clear();
  66229. this.onBeforeRenderObservable.clear();
  66230. this.onSizeChangedObservable.clear();
  66231. };
  66232. return PostProcess;
  66233. }());
  66234. BABYLON.PostProcess = PostProcess;
  66235. })(BABYLON || (BABYLON = {}));
  66236. //# sourceMappingURL=babylon.postProcess.js.map
  66237. var BABYLON;
  66238. (function (BABYLON) {
  66239. var PassPostProcess = /** @class */ (function (_super) {
  66240. __extends(PassPostProcess, _super);
  66241. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66242. if (camera === void 0) { camera = null; }
  66243. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66244. if (blockCompilation === void 0) { blockCompilation = false; }
  66245. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66246. }
  66247. return PassPostProcess;
  66248. }(BABYLON.PostProcess));
  66249. BABYLON.PassPostProcess = PassPostProcess;
  66250. })(BABYLON || (BABYLON = {}));
  66251. //# sourceMappingURL=babylon.passPostProcess.js.map
  66252. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66253. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66254. s = arguments[i];
  66255. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66256. t[p] = s[p];
  66257. }
  66258. return t;
  66259. };
  66260. var BABYLON;
  66261. (function (BABYLON) {
  66262. /**
  66263. * Default implementation IShadowGenerator.
  66264. * This is the main object responsible of generating shadows in the framework.
  66265. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66266. */
  66267. var ShadowGenerator = /** @class */ (function () {
  66268. /**
  66269. * Creates a ShadowGenerator object.
  66270. * A ShadowGenerator is the required tool to use the shadows.
  66271. * Each light casting shadows needs to use its own ShadowGenerator.
  66272. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66273. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66274. * @param light The light object generating the shadows.
  66275. * @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.
  66276. */
  66277. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66278. this._bias = 0.00005;
  66279. this._normalBias = 0;
  66280. this._blurBoxOffset = 1;
  66281. this._blurScale = 2;
  66282. this._blurKernel = 1;
  66283. this._useKernelBlur = false;
  66284. this._filter = ShadowGenerator.FILTER_NONE;
  66285. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66286. this._contactHardeningLightSizeUVRatio = 0.1;
  66287. this._darkness = 0;
  66288. this._transparencyShadow = false;
  66289. /**
  66290. * Controls the extent to which the shadows fade out at the edge of the frustum
  66291. * Used only by directionals and spots
  66292. */
  66293. this.frustumEdgeFalloff = 0;
  66294. /**
  66295. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66296. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66297. * It might on the other hand introduce peter panning.
  66298. */
  66299. this.forceBackFacesOnly = false;
  66300. this._lightDirection = BABYLON.Vector3.Zero();
  66301. this._viewMatrix = BABYLON.Matrix.Zero();
  66302. this._projectionMatrix = BABYLON.Matrix.Zero();
  66303. this._transformMatrix = BABYLON.Matrix.Zero();
  66304. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66305. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66306. this._currentFaceIndex = 0;
  66307. this._currentFaceIndexCache = 0;
  66308. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66309. this._mapSize = mapSize;
  66310. this._light = light;
  66311. this._scene = light.getScene();
  66312. light._shadowGenerator = this;
  66313. // Texture type fallback from float to int if not supported.
  66314. var caps = this._scene.getEngine().getCaps();
  66315. if (!useFullFloatFirst) {
  66316. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66317. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66318. }
  66319. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66320. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66321. }
  66322. else {
  66323. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66324. }
  66325. }
  66326. else {
  66327. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66328. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66329. }
  66330. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66331. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66332. }
  66333. else {
  66334. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66335. }
  66336. }
  66337. this._initializeGenerator();
  66338. this._applyFilterValues();
  66339. }
  66340. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66341. /**
  66342. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66343. */
  66344. get: function () {
  66345. return this._bias;
  66346. },
  66347. /**
  66348. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66349. */
  66350. set: function (bias) {
  66351. this._bias = bias;
  66352. },
  66353. enumerable: true,
  66354. configurable: true
  66355. });
  66356. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66357. /**
  66358. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66359. */
  66360. get: function () {
  66361. return this._normalBias;
  66362. },
  66363. /**
  66364. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66365. */
  66366. set: function (normalBias) {
  66367. this._normalBias = normalBias;
  66368. },
  66369. enumerable: true,
  66370. configurable: true
  66371. });
  66372. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66373. /**
  66374. * Gets the blur box offset: offset applied during the blur pass.
  66375. * Only usefull if useKernelBlur = false
  66376. */
  66377. get: function () {
  66378. return this._blurBoxOffset;
  66379. },
  66380. /**
  66381. * Sets the blur box offset: offset applied during the blur pass.
  66382. * Only usefull if useKernelBlur = false
  66383. */
  66384. set: function (value) {
  66385. if (this._blurBoxOffset === value) {
  66386. return;
  66387. }
  66388. this._blurBoxOffset = value;
  66389. this._disposeBlurPostProcesses();
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66395. /**
  66396. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66397. * 2 means half of the size.
  66398. */
  66399. get: function () {
  66400. return this._blurScale;
  66401. },
  66402. /**
  66403. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66404. * 2 means half of the size.
  66405. */
  66406. set: function (value) {
  66407. if (this._blurScale === value) {
  66408. return;
  66409. }
  66410. this._blurScale = value;
  66411. this._disposeBlurPostProcesses();
  66412. },
  66413. enumerable: true,
  66414. configurable: true
  66415. });
  66416. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66417. /**
  66418. * Gets the blur kernel: kernel size of the blur pass.
  66419. * Only usefull if useKernelBlur = true
  66420. */
  66421. get: function () {
  66422. return this._blurKernel;
  66423. },
  66424. /**
  66425. * Sets the blur kernel: kernel size of the blur pass.
  66426. * Only usefull if useKernelBlur = true
  66427. */
  66428. set: function (value) {
  66429. if (this._blurKernel === value) {
  66430. return;
  66431. }
  66432. this._blurKernel = value;
  66433. this._disposeBlurPostProcesses();
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66439. /**
  66440. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66441. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66442. */
  66443. get: function () {
  66444. return this._useKernelBlur;
  66445. },
  66446. /**
  66447. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66448. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66449. */
  66450. set: function (value) {
  66451. if (this._useKernelBlur === value) {
  66452. return;
  66453. }
  66454. this._useKernelBlur = value;
  66455. this._disposeBlurPostProcesses();
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66461. /**
  66462. * Gets the depth scale used in ESM mode.
  66463. */
  66464. get: function () {
  66465. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66466. },
  66467. /**
  66468. * Sets the depth scale used in ESM mode.
  66469. * This can override the scale stored on the light.
  66470. */
  66471. set: function (value) {
  66472. this._depthScale = value;
  66473. },
  66474. enumerable: true,
  66475. configurable: true
  66476. });
  66477. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66478. /**
  66479. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66480. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66481. */
  66482. get: function () {
  66483. return this._filter;
  66484. },
  66485. /**
  66486. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66487. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66488. */
  66489. set: function (value) {
  66490. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66491. if (this._light.needCube()) {
  66492. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66493. this.useExponentialShadowMap = true;
  66494. return;
  66495. }
  66496. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66497. this.useCloseExponentialShadowMap = true;
  66498. return;
  66499. }
  66500. // PCF on cubemap would also be expensive
  66501. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66502. this.usePoissonSampling = true;
  66503. return;
  66504. }
  66505. }
  66506. // Weblg1 fallback for PCF.
  66507. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66508. if (this._scene.getEngine().webGLVersion === 1) {
  66509. this.usePoissonSampling = true;
  66510. return;
  66511. }
  66512. }
  66513. if (this._filter === value) {
  66514. return;
  66515. }
  66516. this._filter = value;
  66517. this._disposeBlurPostProcesses();
  66518. this._applyFilterValues();
  66519. this._light._markMeshesAsLightDirty();
  66520. },
  66521. enumerable: true,
  66522. configurable: true
  66523. });
  66524. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66525. /**
  66526. * Gets if the current filter is set to Poisson Sampling.
  66527. */
  66528. get: function () {
  66529. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66530. },
  66531. /**
  66532. * Sets the current filter to Poisson Sampling.
  66533. */
  66534. set: function (value) {
  66535. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66536. return;
  66537. }
  66538. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66539. },
  66540. enumerable: true,
  66541. configurable: true
  66542. });
  66543. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66544. /**
  66545. * Gets if the current filter is set to VSM.
  66546. * DEPRECATED. Should use useExponentialShadowMap instead.
  66547. */
  66548. get: function () {
  66549. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66550. return this.useExponentialShadowMap;
  66551. },
  66552. /**
  66553. * Sets the current filter is to VSM.
  66554. * DEPRECATED. Should use useExponentialShadowMap instead.
  66555. */
  66556. set: function (value) {
  66557. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66558. this.useExponentialShadowMap = value;
  66559. },
  66560. enumerable: true,
  66561. configurable: true
  66562. });
  66563. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66564. /**
  66565. * Gets if the current filter is set to blurred VSM.
  66566. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66567. */
  66568. get: function () {
  66569. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66570. return this.useBlurExponentialShadowMap;
  66571. },
  66572. /**
  66573. * Sets the current filter is to blurred VSM.
  66574. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66575. */
  66576. set: function (value) {
  66577. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66578. this.useBlurExponentialShadowMap = value;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66584. /**
  66585. * Gets if the current filter is set to ESM.
  66586. */
  66587. get: function () {
  66588. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66589. },
  66590. /**
  66591. * Sets the current filter is to ESM.
  66592. */
  66593. set: function (value) {
  66594. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66595. return;
  66596. }
  66597. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66598. },
  66599. enumerable: true,
  66600. configurable: true
  66601. });
  66602. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66603. /**
  66604. * Gets if the current filter is set to filtered ESM.
  66605. */
  66606. get: function () {
  66607. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66608. },
  66609. /**
  66610. * Gets if the current filter is set to filtered ESM.
  66611. */
  66612. set: function (value) {
  66613. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66614. return;
  66615. }
  66616. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66617. },
  66618. enumerable: true,
  66619. configurable: true
  66620. });
  66621. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66622. /**
  66623. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66624. * exponential to prevent steep falloff artifacts).
  66625. */
  66626. get: function () {
  66627. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66628. },
  66629. /**
  66630. * Sets the current filter to "close ESM" (using the inverse of the
  66631. * exponential to prevent steep falloff artifacts).
  66632. */
  66633. set: function (value) {
  66634. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66635. return;
  66636. }
  66637. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66638. },
  66639. enumerable: true,
  66640. configurable: true
  66641. });
  66642. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66643. /**
  66644. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66645. * exponential to prevent steep falloff artifacts).
  66646. */
  66647. get: function () {
  66648. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66649. },
  66650. /**
  66651. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66652. * exponential to prevent steep falloff artifacts).
  66653. */
  66654. set: function (value) {
  66655. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66656. return;
  66657. }
  66658. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66659. },
  66660. enumerable: true,
  66661. configurable: true
  66662. });
  66663. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66664. /**
  66665. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66666. */
  66667. get: function () {
  66668. return this.filter === ShadowGenerator.FILTER_PCF;
  66669. },
  66670. /**
  66671. * Sets the current filter to "PCF" (percentage closer filtering).
  66672. */
  66673. set: function (value) {
  66674. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66675. return;
  66676. }
  66677. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66678. },
  66679. enumerable: true,
  66680. configurable: true
  66681. });
  66682. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66683. /**
  66684. * Gets the PCF or PCSS Quality.
  66685. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66686. */
  66687. get: function () {
  66688. return this._filteringQuality;
  66689. },
  66690. /**
  66691. * Sets the PCF or PCSS Quality.
  66692. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66693. */
  66694. set: function (filteringQuality) {
  66695. this._filteringQuality = filteringQuality;
  66696. },
  66697. enumerable: true,
  66698. configurable: true
  66699. });
  66700. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66701. /**
  66702. * Gets if the current filter is set to "PCSS" (contact hardening).
  66703. */
  66704. get: function () {
  66705. return this.filter === ShadowGenerator.FILTER_PCSS;
  66706. },
  66707. /**
  66708. * Sets the current filter to "PCSS" (contact hardening).
  66709. */
  66710. set: function (value) {
  66711. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66712. return;
  66713. }
  66714. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66715. },
  66716. enumerable: true,
  66717. configurable: true
  66718. });
  66719. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66720. /**
  66721. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66722. * Using a ratio helps keeping shape stability independently of the map size.
  66723. *
  66724. * It does not account for the light projection as it was having too much
  66725. * instability during the light setup or during light position changes.
  66726. *
  66727. * Only valid if useContactHardeningShadow is true.
  66728. */
  66729. get: function () {
  66730. return this._contactHardeningLightSizeUVRatio;
  66731. },
  66732. /**
  66733. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66734. * Using a ratio helps keeping shape stability independently of the map size.
  66735. *
  66736. * It does not account for the light projection as it was having too much
  66737. * instability during the light setup or during light position changes.
  66738. *
  66739. * Only valid if useContactHardeningShadow is true.
  66740. */
  66741. set: function (contactHardeningLightSizeUVRatio) {
  66742. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66743. },
  66744. enumerable: true,
  66745. configurable: true
  66746. });
  66747. /**
  66748. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66749. * 0 means strongest and 1 would means no shadow.
  66750. * @returns the darkness.
  66751. */
  66752. ShadowGenerator.prototype.getDarkness = function () {
  66753. return this._darkness;
  66754. };
  66755. /**
  66756. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66757. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66758. * @returns the shadow generator allowing fluent coding.
  66759. */
  66760. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66761. if (darkness >= 1.0)
  66762. this._darkness = 1.0;
  66763. else if (darkness <= 0.0)
  66764. this._darkness = 0.0;
  66765. else
  66766. this._darkness = darkness;
  66767. return this;
  66768. };
  66769. /**
  66770. * Sets the ability to have transparent shadow (boolean).
  66771. * @param transparent True if transparent else False
  66772. * @returns the shadow generator allowing fluent coding
  66773. */
  66774. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66775. this._transparencyShadow = transparent;
  66776. return this;
  66777. };
  66778. /**
  66779. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66780. * @returns The render target texture if present otherwise, null
  66781. */
  66782. ShadowGenerator.prototype.getShadowMap = function () {
  66783. return this._shadowMap;
  66784. };
  66785. /**
  66786. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66787. * @returns The render target texture if the shadow map is present otherwise, null
  66788. */
  66789. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66790. if (this._shadowMap2) {
  66791. return this._shadowMap2;
  66792. }
  66793. return this._shadowMap;
  66794. };
  66795. /**
  66796. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66797. * @param mesh Mesh to add
  66798. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66799. * @returns the Shadow Generator itself
  66800. */
  66801. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66802. if (includeDescendants === void 0) { includeDescendants = true; }
  66803. if (!this._shadowMap) {
  66804. return this;
  66805. }
  66806. if (!this._shadowMap.renderList) {
  66807. this._shadowMap.renderList = [];
  66808. }
  66809. this._shadowMap.renderList.push(mesh);
  66810. if (includeDescendants) {
  66811. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66812. }
  66813. return this;
  66814. var _a;
  66815. };
  66816. /**
  66817. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66818. * @param mesh Mesh to remove
  66819. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66820. * @returns the Shadow Generator itself
  66821. */
  66822. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66823. if (includeDescendants === void 0) { includeDescendants = true; }
  66824. if (!this._shadowMap || !this._shadowMap.renderList) {
  66825. return this;
  66826. }
  66827. var index = this._shadowMap.renderList.indexOf(mesh);
  66828. if (index !== -1) {
  66829. this._shadowMap.renderList.splice(index, 1);
  66830. }
  66831. if (includeDescendants) {
  66832. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66833. var child = _a[_i];
  66834. this.removeShadowCaster(child);
  66835. }
  66836. }
  66837. return this;
  66838. };
  66839. /**
  66840. * Returns the associated light object.
  66841. * @returns the light generating the shadow
  66842. */
  66843. ShadowGenerator.prototype.getLight = function () {
  66844. return this._light;
  66845. };
  66846. ShadowGenerator.prototype._initializeGenerator = function () {
  66847. this._light._markMeshesAsLightDirty();
  66848. this._initializeShadowMap();
  66849. };
  66850. ShadowGenerator.prototype._initializeShadowMap = function () {
  66851. var _this = this;
  66852. // Render target
  66853. var engine = this._scene.getEngine();
  66854. if (engine.webGLVersion > 1) {
  66855. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66856. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66857. }
  66858. else {
  66859. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66860. }
  66861. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66862. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66863. this._shadowMap.anisotropicFilteringLevel = 1;
  66864. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66865. this._shadowMap.renderParticles = false;
  66866. this._shadowMap.ignoreCameraViewport = true;
  66867. // Record Face Index before render.
  66868. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66869. _this._currentFaceIndex = faceIndex;
  66870. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66871. engine.setColorWrite(false);
  66872. }
  66873. });
  66874. // Custom render function.
  66875. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66876. // Blur if required afer render.
  66877. this._shadowMap.onAfterUnbindObservable.add(function () {
  66878. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66879. engine.setColorWrite(true);
  66880. }
  66881. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66882. return;
  66883. }
  66884. var shadowMap = _this.getShadowMapForRendering();
  66885. if (shadowMap) {
  66886. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66887. }
  66888. });
  66889. // Clear according to the chosen filter.
  66890. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66891. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66892. this._shadowMap.onClearObservable.add(function (engine) {
  66893. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66894. engine.clear(clearOne, false, true, false);
  66895. }
  66896. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66897. engine.clear(clearZero, true, true, false);
  66898. }
  66899. else {
  66900. engine.clear(clearOne, true, true, false);
  66901. }
  66902. });
  66903. };
  66904. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66905. var _this = this;
  66906. var engine = this._scene.getEngine();
  66907. var targetSize = this._mapSize / this.blurScale;
  66908. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66909. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66910. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66911. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66912. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66913. }
  66914. if (this.useKernelBlur) {
  66915. 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);
  66916. this._kernelBlurXPostprocess.width = targetSize;
  66917. this._kernelBlurXPostprocess.height = targetSize;
  66918. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66919. effect.setTexture("textureSampler", _this._shadowMap);
  66920. });
  66921. 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);
  66922. this._kernelBlurXPostprocess.autoClear = false;
  66923. this._kernelBlurYPostprocess.autoClear = false;
  66924. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66925. this._kernelBlurXPostprocess.packedFloat = true;
  66926. this._kernelBlurYPostprocess.packedFloat = true;
  66927. }
  66928. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66929. }
  66930. else {
  66931. 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);
  66932. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66933. effect.setFloat2("screenSize", targetSize, targetSize);
  66934. effect.setTexture("textureSampler", _this._shadowMap);
  66935. });
  66936. this._boxBlurPostprocess.autoClear = false;
  66937. this._blurPostProcesses = [this._boxBlurPostprocess];
  66938. }
  66939. };
  66940. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66941. var index;
  66942. var engine = this._scene.getEngine();
  66943. if (depthOnlySubMeshes.length) {
  66944. engine.setColorWrite(false);
  66945. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66946. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66947. }
  66948. engine.setColorWrite(true);
  66949. }
  66950. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66951. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66952. }
  66953. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66954. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66955. }
  66956. if (this._transparencyShadow) {
  66957. for (index = 0; index < transparentSubMeshes.length; index++) {
  66958. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66959. }
  66960. }
  66961. };
  66962. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66963. var _this = this;
  66964. var mesh = subMesh.getRenderingMesh();
  66965. var scene = this._scene;
  66966. var engine = scene.getEngine();
  66967. var material = subMesh.getMaterial();
  66968. if (!material) {
  66969. return;
  66970. }
  66971. // Culling
  66972. engine.setState(material.backFaceCulling);
  66973. // Managing instances
  66974. var batch = mesh._getInstancesRenderList(subMesh._id);
  66975. if (batch.mustReturn) {
  66976. return;
  66977. }
  66978. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66979. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66980. engine.enableEffect(this._effect);
  66981. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66982. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66983. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66984. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66985. this._effect.setVector3("lightData", this._cachedDirection);
  66986. }
  66987. else {
  66988. this._effect.setVector3("lightData", this._cachedPosition);
  66989. }
  66990. if (scene.activeCamera) {
  66991. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66992. }
  66993. // Alpha test
  66994. if (material && material.needAlphaTesting()) {
  66995. var alphaTexture = material.getAlphaTestTexture();
  66996. if (alphaTexture) {
  66997. this._effect.setTexture("diffuseSampler", alphaTexture);
  66998. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66999. }
  67000. }
  67001. // Bones
  67002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67003. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  67004. }
  67005. // Morph targets
  67006. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  67007. if (this.forceBackFacesOnly) {
  67008. engine.setState(true, 0, false, true);
  67009. }
  67010. // Draw
  67011. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67012. if (this.forceBackFacesOnly) {
  67013. engine.setState(true, 0, false, false);
  67014. }
  67015. }
  67016. else {
  67017. // Need to reset refresh rate of the shadowMap
  67018. if (this._shadowMap) {
  67019. this._shadowMap.resetRefreshCounter();
  67020. }
  67021. }
  67022. };
  67023. ShadowGenerator.prototype._applyFilterValues = function () {
  67024. if (!this._shadowMap) {
  67025. return;
  67026. }
  67027. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  67028. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67029. }
  67030. else {
  67031. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67032. }
  67033. };
  67034. /**
  67035. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67036. * @param onCompiled Callback triggered at the and of the effects compilation
  67037. * @param options Sets of optional options forcing the compilation with different modes
  67038. */
  67039. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  67040. var _this = this;
  67041. var localOptions = __assign({ useInstances: false }, options);
  67042. var shadowMap = this.getShadowMap();
  67043. if (!shadowMap) {
  67044. if (onCompiled) {
  67045. onCompiled(this);
  67046. }
  67047. return;
  67048. }
  67049. var renderList = shadowMap.renderList;
  67050. if (!renderList) {
  67051. if (onCompiled) {
  67052. onCompiled(this);
  67053. }
  67054. return;
  67055. }
  67056. var subMeshes = new Array();
  67057. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  67058. var mesh = renderList_1[_i];
  67059. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  67060. }
  67061. if (subMeshes.length === 0) {
  67062. if (onCompiled) {
  67063. onCompiled(this);
  67064. }
  67065. return;
  67066. }
  67067. var currentIndex = 0;
  67068. var checkReady = function () {
  67069. if (!_this._scene || !_this._scene.getEngine()) {
  67070. return;
  67071. }
  67072. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  67073. currentIndex++;
  67074. if (currentIndex >= subMeshes.length) {
  67075. if (onCompiled) {
  67076. onCompiled(_this);
  67077. }
  67078. return;
  67079. }
  67080. }
  67081. setTimeout(checkReady, 16);
  67082. };
  67083. checkReady();
  67084. };
  67085. /**
  67086. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67087. * @param options Sets of optional options forcing the compilation with different modes
  67088. * @returns A promise that resolves when the compilation completes
  67089. */
  67090. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  67091. var _this = this;
  67092. return new Promise(function (resolve) {
  67093. _this.forceCompilation(function () {
  67094. resolve();
  67095. }, options);
  67096. });
  67097. };
  67098. /**
  67099. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67100. * @param subMesh The submesh we want to render in the shadow map
  67101. * @param useInstances Defines wether will draw in the map using instances
  67102. * @returns true if ready otherwise, false
  67103. */
  67104. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67105. var defines = [];
  67106. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67107. defines.push("#define FLOAT");
  67108. }
  67109. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67110. defines.push("#define ESM");
  67111. }
  67112. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67113. defines.push("#define DEPTHTEXTURE");
  67114. }
  67115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67116. var mesh = subMesh.getMesh();
  67117. var material = subMesh.getMaterial();
  67118. // Normal bias.
  67119. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67120. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67121. defines.push("#define NORMAL");
  67122. if (mesh.nonUniformScaling) {
  67123. defines.push("#define NONUNIFORMSCALING");
  67124. }
  67125. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67126. defines.push("#define DIRECTIONINLIGHTDATA");
  67127. }
  67128. }
  67129. // Alpha test
  67130. if (material && material.needAlphaTesting()) {
  67131. var alphaTexture = material.getAlphaTestTexture();
  67132. if (alphaTexture) {
  67133. defines.push("#define ALPHATEST");
  67134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67135. attribs.push(BABYLON.VertexBuffer.UVKind);
  67136. defines.push("#define UV1");
  67137. }
  67138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67139. if (alphaTexture.coordinatesIndex === 1) {
  67140. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67141. defines.push("#define UV2");
  67142. }
  67143. }
  67144. }
  67145. }
  67146. // Bones
  67147. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67148. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67149. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67150. if (mesh.numBoneInfluencers > 4) {
  67151. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67152. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67153. }
  67154. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67155. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67156. }
  67157. else {
  67158. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67159. }
  67160. // Morph targets
  67161. var manager = mesh.morphTargetManager;
  67162. var morphInfluencers = 0;
  67163. if (manager) {
  67164. if (manager.numInfluencers > 0) {
  67165. defines.push("#define MORPHTARGETS");
  67166. morphInfluencers = manager.numInfluencers;
  67167. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67168. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67169. }
  67170. }
  67171. // Instances
  67172. if (useInstances) {
  67173. defines.push("#define INSTANCES");
  67174. attribs.push("world0");
  67175. attribs.push("world1");
  67176. attribs.push("world2");
  67177. attribs.push("world3");
  67178. }
  67179. // Get correct effect
  67180. var join = defines.join("\n");
  67181. if (this._cachedDefines !== join) {
  67182. this._cachedDefines = join;
  67183. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67184. }
  67185. if (!this._effect.isReady()) {
  67186. return false;
  67187. }
  67188. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67189. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67190. this._initializeBlurRTTAndPostProcesses();
  67191. }
  67192. }
  67193. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67194. return false;
  67195. }
  67196. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67197. return false;
  67198. }
  67199. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67200. return false;
  67201. }
  67202. return true;
  67203. };
  67204. /**
  67205. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67206. * @param defines Defines of the material we want to update
  67207. * @param lightIndex Index of the light in the enabled light list of the material
  67208. */
  67209. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67210. var scene = this._scene;
  67211. var light = this._light;
  67212. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67213. return;
  67214. }
  67215. defines["SHADOW" + lightIndex] = true;
  67216. if (this.useContactHardeningShadow) {
  67217. defines["SHADOWPCSS" + lightIndex] = true;
  67218. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67219. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67220. }
  67221. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67222. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67223. }
  67224. // else default to high.
  67225. }
  67226. if (this.usePercentageCloserFiltering) {
  67227. defines["SHADOWPCF" + lightIndex] = true;
  67228. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67229. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67230. }
  67231. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67232. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67233. }
  67234. // else default to high.
  67235. }
  67236. else if (this.usePoissonSampling) {
  67237. defines["SHADOWPOISSON" + lightIndex] = true;
  67238. }
  67239. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67240. defines["SHADOWESM" + lightIndex] = true;
  67241. }
  67242. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67243. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67244. }
  67245. if (light.needCube()) {
  67246. defines["SHADOWCUBE" + lightIndex] = true;
  67247. }
  67248. };
  67249. /**
  67250. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67251. * defined in the generator but impacting the effect).
  67252. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67253. * @param effect The effect we are binfing the information for
  67254. */
  67255. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67256. var light = this._light;
  67257. var scene = this._scene;
  67258. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67259. return;
  67260. }
  67261. var camera = scene.activeCamera;
  67262. if (!camera) {
  67263. return;
  67264. }
  67265. var shadowMap = this.getShadowMap();
  67266. if (!shadowMap) {
  67267. return;
  67268. }
  67269. if (!light.needCube()) {
  67270. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67271. }
  67272. // Only PCF uses depth stencil texture.
  67273. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67274. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67275. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67276. }
  67277. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67278. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67279. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67280. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67281. }
  67282. else {
  67283. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67284. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67285. }
  67286. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67287. };
  67288. /**
  67289. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67290. * (eq to shadow prjection matrix * light transform matrix)
  67291. * @returns The transform matrix used to create the shadow map
  67292. */
  67293. ShadowGenerator.prototype.getTransformMatrix = function () {
  67294. var scene = this._scene;
  67295. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67296. return this._transformMatrix;
  67297. }
  67298. this._currentRenderID = scene.getRenderId();
  67299. this._currentFaceIndexCache = this._currentFaceIndex;
  67300. var lightPosition = this._light.position;
  67301. if (this._light.computeTransformedInformation()) {
  67302. lightPosition = this._light.transformedPosition;
  67303. }
  67304. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67305. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67306. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67307. }
  67308. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67309. this._cachedPosition.copyFrom(lightPosition);
  67310. this._cachedDirection.copyFrom(this._lightDirection);
  67311. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67312. var shadowMap = this.getShadowMap();
  67313. if (shadowMap) {
  67314. var renderList = shadowMap.renderList;
  67315. if (renderList) {
  67316. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67317. }
  67318. }
  67319. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67320. }
  67321. return this._transformMatrix;
  67322. };
  67323. /**
  67324. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67325. * Cube and 2D textures for instance.
  67326. */
  67327. ShadowGenerator.prototype.recreateShadowMap = function () {
  67328. var shadowMap = this._shadowMap;
  67329. if (!shadowMap) {
  67330. return;
  67331. }
  67332. // Track render list.
  67333. var renderList = shadowMap.renderList;
  67334. // Clean up existing data.
  67335. this._disposeRTTandPostProcesses();
  67336. // Reinitializes.
  67337. this._initializeGenerator();
  67338. // Reaffect the filter to ensure a correct fallback if necessary.
  67339. this.filter = this.filter;
  67340. // Reaffect the filter.
  67341. this._applyFilterValues();
  67342. // Reaffect Render List.
  67343. this._shadowMap.renderList = renderList;
  67344. };
  67345. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67346. if (this._shadowMap2) {
  67347. this._shadowMap2.dispose();
  67348. this._shadowMap2 = null;
  67349. }
  67350. if (this._boxBlurPostprocess) {
  67351. this._boxBlurPostprocess.dispose();
  67352. this._boxBlurPostprocess = null;
  67353. }
  67354. if (this._kernelBlurXPostprocess) {
  67355. this._kernelBlurXPostprocess.dispose();
  67356. this._kernelBlurXPostprocess = null;
  67357. }
  67358. if (this._kernelBlurYPostprocess) {
  67359. this._kernelBlurYPostprocess.dispose();
  67360. this._kernelBlurYPostprocess = null;
  67361. }
  67362. this._blurPostProcesses = [];
  67363. };
  67364. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67365. if (this._shadowMap) {
  67366. this._shadowMap.dispose();
  67367. this._shadowMap = null;
  67368. }
  67369. this._disposeBlurPostProcesses();
  67370. };
  67371. /**
  67372. * Disposes the ShadowGenerator.
  67373. * Returns nothing.
  67374. */
  67375. ShadowGenerator.prototype.dispose = function () {
  67376. this._disposeRTTandPostProcesses();
  67377. if (this._light) {
  67378. this._light._shadowGenerator = null;
  67379. this._light._markMeshesAsLightDirty();
  67380. }
  67381. };
  67382. /**
  67383. * Serializes the shadow generator setup to a json object.
  67384. * @returns The serialized JSON object
  67385. */
  67386. ShadowGenerator.prototype.serialize = function () {
  67387. var serializationObject = {};
  67388. var shadowMap = this.getShadowMap();
  67389. if (!shadowMap) {
  67390. return serializationObject;
  67391. }
  67392. serializationObject.lightId = this._light.id;
  67393. serializationObject.mapSize = shadowMap.getRenderSize();
  67394. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67395. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67396. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67397. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67398. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67399. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67400. serializationObject.depthScale = this.depthScale;
  67401. serializationObject.darkness = this.getDarkness();
  67402. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67403. serializationObject.blurKernel = this.blurKernel;
  67404. serializationObject.blurScale = this.blurScale;
  67405. serializationObject.useKernelBlur = this.useKernelBlur;
  67406. serializationObject.transparencyShadow = this._transparencyShadow;
  67407. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67408. serializationObject.bias = this.bias;
  67409. serializationObject.normalBias = this.normalBias;
  67410. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67411. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67412. serializationObject.filteringQuality = this.filteringQuality;
  67413. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67414. serializationObject.renderList = [];
  67415. if (shadowMap.renderList) {
  67416. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67417. var mesh = shadowMap.renderList[meshIndex];
  67418. serializationObject.renderList.push(mesh.id);
  67419. }
  67420. }
  67421. return serializationObject;
  67422. };
  67423. /**
  67424. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67425. * @param parsedShadowGenerator The JSON object to parse
  67426. * @param scene The scene to create the shadow map for
  67427. * @returns The parsed shadow generator
  67428. */
  67429. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67430. //casting to point light, as light is missing the position attr and typescript complains.
  67431. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67432. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67433. var shadowMap = shadowGenerator.getShadowMap();
  67434. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67435. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67436. meshes.forEach(function (mesh) {
  67437. if (!shadowMap) {
  67438. return;
  67439. }
  67440. if (!shadowMap.renderList) {
  67441. shadowMap.renderList = [];
  67442. }
  67443. shadowMap.renderList.push(mesh);
  67444. });
  67445. }
  67446. if (parsedShadowGenerator.usePoissonSampling) {
  67447. shadowGenerator.usePoissonSampling = true;
  67448. }
  67449. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67450. shadowGenerator.useExponentialShadowMap = true;
  67451. }
  67452. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67453. shadowGenerator.useBlurExponentialShadowMap = true;
  67454. }
  67455. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67456. shadowGenerator.useCloseExponentialShadowMap = true;
  67457. }
  67458. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67459. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67460. }
  67461. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67462. shadowGenerator.usePercentageCloserFiltering = true;
  67463. }
  67464. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67465. shadowGenerator.useContactHardeningShadow = true;
  67466. }
  67467. if (parsedShadowGenerator.filteringQuality) {
  67468. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67469. }
  67470. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67471. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67472. }
  67473. // Backward compat
  67474. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67475. shadowGenerator.useExponentialShadowMap = true;
  67476. }
  67477. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67478. shadowGenerator.useBlurExponentialShadowMap = true;
  67479. }
  67480. if (parsedShadowGenerator.depthScale) {
  67481. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67482. }
  67483. if (parsedShadowGenerator.blurScale) {
  67484. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67485. }
  67486. if (parsedShadowGenerator.blurBoxOffset) {
  67487. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67488. }
  67489. if (parsedShadowGenerator.useKernelBlur) {
  67490. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67491. }
  67492. if (parsedShadowGenerator.blurKernel) {
  67493. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67494. }
  67495. if (parsedShadowGenerator.bias !== undefined) {
  67496. shadowGenerator.bias = parsedShadowGenerator.bias;
  67497. }
  67498. if (parsedShadowGenerator.normalBias !== undefined) {
  67499. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67500. }
  67501. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67502. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67503. }
  67504. if (parsedShadowGenerator.darkness) {
  67505. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67506. }
  67507. if (parsedShadowGenerator.transparencyShadow) {
  67508. shadowGenerator.setTransparencyShadow(true);
  67509. }
  67510. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67511. return shadowGenerator;
  67512. };
  67513. /**
  67514. * Shadow generator mode None: no filtering applied.
  67515. */
  67516. ShadowGenerator.FILTER_NONE = 0;
  67517. /**
  67518. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67519. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67520. */
  67521. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67522. /**
  67523. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67524. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67525. */
  67526. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67527. /**
  67528. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67529. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67530. */
  67531. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67532. /**
  67533. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67534. * edge artifacts on steep falloff.
  67535. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67536. */
  67537. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67538. /**
  67539. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67540. * edge artifacts on steep falloff.
  67541. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67542. */
  67543. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67544. /**
  67545. * Shadow generator mode PCF: Percentage Closer Filtering
  67546. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67547. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67548. */
  67549. ShadowGenerator.FILTER_PCF = 6;
  67550. /**
  67551. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67552. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67553. * Contact Hardening
  67554. */
  67555. ShadowGenerator.FILTER_PCSS = 7;
  67556. /**
  67557. * Reserved for PCF and PCSS
  67558. * Highest Quality.
  67559. *
  67560. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67561. *
  67562. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67563. */
  67564. ShadowGenerator.QUALITY_HIGH = 0;
  67565. /**
  67566. * Reserved for PCF and PCSS
  67567. * Good tradeoff for quality/perf cross devices
  67568. *
  67569. * Execute PCF on a 3*3 kernel.
  67570. *
  67571. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67572. */
  67573. ShadowGenerator.QUALITY_MEDIUM = 1;
  67574. /**
  67575. * Reserved for PCF and PCSS
  67576. * The lowest quality but the fastest.
  67577. *
  67578. * Execute PCF on a 1*1 kernel.
  67579. *
  67580. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67581. */
  67582. ShadowGenerator.QUALITY_LOW = 2;
  67583. return ShadowGenerator;
  67584. }());
  67585. BABYLON.ShadowGenerator = ShadowGenerator;
  67586. })(BABYLON || (BABYLON = {}));
  67587. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67588. var BABYLON;
  67589. (function (BABYLON) {
  67590. var DefaultLoadingScreen = /** @class */ (function () {
  67591. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67592. if (_loadingText === void 0) { _loadingText = ""; }
  67593. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67594. var _this = this;
  67595. this._renderingCanvas = _renderingCanvas;
  67596. this._loadingText = _loadingText;
  67597. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67598. // Resize
  67599. this._resizeLoadingUI = function () {
  67600. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67601. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67602. if (!_this._loadingDiv) {
  67603. return;
  67604. }
  67605. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67606. _this._loadingDiv.style.left = canvasRect.left + "px";
  67607. _this._loadingDiv.style.top = canvasRect.top + "px";
  67608. _this._loadingDiv.style.width = canvasRect.width + "px";
  67609. _this._loadingDiv.style.height = canvasRect.height + "px";
  67610. };
  67611. }
  67612. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67613. if (this._loadingDiv) {
  67614. // Do not add a loading screen if there is already one
  67615. return;
  67616. }
  67617. this._loadingDiv = document.createElement("div");
  67618. this._loadingDiv.id = "babylonjsLoadingDiv";
  67619. this._loadingDiv.style.opacity = "0";
  67620. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67621. this._loadingDiv.style.pointerEvents = "none";
  67622. // Loading text
  67623. this._loadingTextDiv = document.createElement("div");
  67624. this._loadingTextDiv.style.position = "absolute";
  67625. this._loadingTextDiv.style.left = "0";
  67626. this._loadingTextDiv.style.top = "50%";
  67627. this._loadingTextDiv.style.marginTop = "80px";
  67628. this._loadingTextDiv.style.width = "100%";
  67629. this._loadingTextDiv.style.height = "20px";
  67630. this._loadingTextDiv.style.fontFamily = "Arial";
  67631. this._loadingTextDiv.style.fontSize = "14px";
  67632. this._loadingTextDiv.style.color = "white";
  67633. this._loadingTextDiv.style.textAlign = "center";
  67634. this._loadingTextDiv.innerHTML = "Loading";
  67635. this._loadingDiv.appendChild(this._loadingTextDiv);
  67636. //set the predefined text
  67637. this._loadingTextDiv.innerHTML = this._loadingText;
  67638. // Generating keyframes
  67639. var style = document.createElement('style');
  67640. style.type = 'text/css';
  67641. 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 }";
  67642. style.innerHTML = keyFrames;
  67643. document.getElementsByTagName('head')[0].appendChild(style);
  67644. // Loading img
  67645. var imgBack = new Image();
  67646. 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";
  67647. imgBack.style.position = "absolute";
  67648. imgBack.style.left = "50%";
  67649. imgBack.style.top = "50%";
  67650. imgBack.style.marginLeft = "-60px";
  67651. imgBack.style.marginTop = "-60px";
  67652. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67653. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67654. imgBack.style.transformOrigin = "50% 50%";
  67655. imgBack.style.webkitTransformOrigin = "50% 50%";
  67656. this._loadingDiv.appendChild(imgBack);
  67657. this._resizeLoadingUI();
  67658. window.addEventListener("resize", this._resizeLoadingUI);
  67659. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67660. document.body.appendChild(this._loadingDiv);
  67661. this._loadingDiv.style.opacity = "1";
  67662. };
  67663. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67664. var _this = this;
  67665. if (!this._loadingDiv) {
  67666. return;
  67667. }
  67668. var onTransitionEnd = function () {
  67669. if (!_this._loadingDiv) {
  67670. return;
  67671. }
  67672. document.body.removeChild(_this._loadingDiv);
  67673. window.removeEventListener("resize", _this._resizeLoadingUI);
  67674. _this._loadingDiv = null;
  67675. };
  67676. this._loadingDiv.style.opacity = "0";
  67677. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67678. };
  67679. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67680. set: function (text) {
  67681. this._loadingText = text;
  67682. if (this._loadingTextDiv) {
  67683. this._loadingTextDiv.innerHTML = this._loadingText;
  67684. }
  67685. },
  67686. enumerable: true,
  67687. configurable: true
  67688. });
  67689. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67690. get: function () {
  67691. return this._loadingDivBackgroundColor;
  67692. },
  67693. set: function (color) {
  67694. this._loadingDivBackgroundColor = color;
  67695. if (!this._loadingDiv) {
  67696. return;
  67697. }
  67698. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67699. },
  67700. enumerable: true,
  67701. configurable: true
  67702. });
  67703. return DefaultLoadingScreen;
  67704. }());
  67705. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67706. })(BABYLON || (BABYLON = {}));
  67707. //# sourceMappingURL=babylon.loadingScreen.js.map
  67708. var BABYLON;
  67709. (function (BABYLON) {
  67710. var SceneLoaderProgressEvent = /** @class */ (function () {
  67711. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67712. this.lengthComputable = lengthComputable;
  67713. this.loaded = loaded;
  67714. this.total = total;
  67715. }
  67716. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67717. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67718. };
  67719. return SceneLoaderProgressEvent;
  67720. }());
  67721. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67722. var SceneLoader = /** @class */ (function () {
  67723. function SceneLoader() {
  67724. }
  67725. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67726. get: function () {
  67727. return 0;
  67728. },
  67729. enumerable: true,
  67730. configurable: true
  67731. });
  67732. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67733. get: function () {
  67734. return 1;
  67735. },
  67736. enumerable: true,
  67737. configurable: true
  67738. });
  67739. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67740. get: function () {
  67741. return 2;
  67742. },
  67743. enumerable: true,
  67744. configurable: true
  67745. });
  67746. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67747. get: function () {
  67748. return 3;
  67749. },
  67750. enumerable: true,
  67751. configurable: true
  67752. });
  67753. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67754. get: function () {
  67755. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67756. },
  67757. set: function (value) {
  67758. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67759. },
  67760. enumerable: true,
  67761. configurable: true
  67762. });
  67763. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67764. get: function () {
  67765. return SceneLoader._ShowLoadingScreen;
  67766. },
  67767. set: function (value) {
  67768. SceneLoader._ShowLoadingScreen = value;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(SceneLoader, "loggingLevel", {
  67774. get: function () {
  67775. return SceneLoader._loggingLevel;
  67776. },
  67777. set: function (value) {
  67778. SceneLoader._loggingLevel = value;
  67779. },
  67780. enumerable: true,
  67781. configurable: true
  67782. });
  67783. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67784. get: function () {
  67785. return SceneLoader._CleanBoneMatrixWeights;
  67786. },
  67787. set: function (value) {
  67788. SceneLoader._CleanBoneMatrixWeights = value;
  67789. },
  67790. enumerable: true,
  67791. configurable: true
  67792. });
  67793. SceneLoader._getDefaultPlugin = function () {
  67794. return SceneLoader._registeredPlugins[".babylon"];
  67795. };
  67796. SceneLoader._getPluginForExtension = function (extension) {
  67797. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67798. if (registeredPlugin) {
  67799. return registeredPlugin;
  67800. }
  67801. 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");
  67802. return SceneLoader._getDefaultPlugin();
  67803. };
  67804. SceneLoader._getPluginForDirectLoad = function (data) {
  67805. for (var extension in SceneLoader._registeredPlugins) {
  67806. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67807. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67808. return SceneLoader._registeredPlugins[extension];
  67809. }
  67810. }
  67811. return SceneLoader._getDefaultPlugin();
  67812. };
  67813. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67814. if (sceneFilename.name) {
  67815. sceneFilename = sceneFilename.name;
  67816. }
  67817. var queryStringPosition = sceneFilename.indexOf("?");
  67818. if (queryStringPosition !== -1) {
  67819. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67820. }
  67821. var dotPosition = sceneFilename.lastIndexOf(".");
  67822. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67823. return SceneLoader._getPluginForExtension(extension);
  67824. };
  67825. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67826. SceneLoader._getDirectLoad = function (sceneFilename) {
  67827. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67828. return sceneFilename.substr(5);
  67829. }
  67830. return null;
  67831. };
  67832. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67833. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67834. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67835. var plugin;
  67836. if (registeredPlugin.plugin.createPlugin) {
  67837. plugin = registeredPlugin.plugin.createPlugin();
  67838. }
  67839. else {
  67840. plugin = registeredPlugin.plugin;
  67841. }
  67842. var useArrayBuffer = registeredPlugin.isBinary;
  67843. var database;
  67844. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67845. var dataCallback = function (data, responseURL) {
  67846. if (scene.isDisposed) {
  67847. onError("Scene has been disposed");
  67848. return;
  67849. }
  67850. scene.database = database;
  67851. onSuccess(plugin, data, responseURL);
  67852. };
  67853. var request = null;
  67854. var pluginDisposed = false;
  67855. var onDisposeObservable = plugin.onDisposeObservable;
  67856. if (onDisposeObservable) {
  67857. onDisposeObservable.add(function () {
  67858. pluginDisposed = true;
  67859. if (request) {
  67860. request.abort();
  67861. request = null;
  67862. }
  67863. onDispose();
  67864. });
  67865. }
  67866. var manifestChecked = function () {
  67867. if (pluginDisposed) {
  67868. return;
  67869. }
  67870. var url = rootUrl + sceneFilename;
  67871. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67872. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67873. } : undefined, database, useArrayBuffer, function (request, exception) {
  67874. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67875. });
  67876. };
  67877. if (directLoad) {
  67878. dataCallback(directLoad);
  67879. return plugin;
  67880. }
  67881. if (rootUrl.indexOf("file:") === -1) {
  67882. var engine = scene.getEngine();
  67883. var canUseOfflineSupport = engine.enableOfflineSupport;
  67884. if (canUseOfflineSupport) {
  67885. // Also check for exceptions
  67886. var exceptionFound = false;
  67887. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67888. var regex = _a[_i];
  67889. if (regex.test(rootUrl + sceneFilename)) {
  67890. exceptionFound = true;
  67891. break;
  67892. }
  67893. }
  67894. canUseOfflineSupport = !exceptionFound;
  67895. }
  67896. if (canUseOfflineSupport) {
  67897. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67898. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67899. }
  67900. else {
  67901. manifestChecked();
  67902. }
  67903. }
  67904. // Loading file from disk via input file or drag'n'drop
  67905. else {
  67906. var fileOrString = sceneFilename;
  67907. if (fileOrString.name) { // File
  67908. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67909. }
  67910. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67911. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67912. }
  67913. else {
  67914. onError("Unable to find file named " + sceneFilename);
  67915. }
  67916. }
  67917. return plugin;
  67918. };
  67919. // Public functions
  67920. SceneLoader.GetPluginForExtension = function (extension) {
  67921. return SceneLoader._getPluginForExtension(extension).plugin;
  67922. };
  67923. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67924. return !!SceneLoader._registeredPlugins[extension];
  67925. };
  67926. SceneLoader.RegisterPlugin = function (plugin) {
  67927. if (typeof plugin.extensions === "string") {
  67928. var extension = plugin.extensions;
  67929. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67930. plugin: plugin,
  67931. isBinary: false
  67932. };
  67933. }
  67934. else {
  67935. var extensions = plugin.extensions;
  67936. Object.keys(extensions).forEach(function (extension) {
  67937. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67938. plugin: plugin,
  67939. isBinary: extensions[extension].isBinary
  67940. };
  67941. });
  67942. }
  67943. };
  67944. /**
  67945. * Import meshes into a scene
  67946. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67947. * @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)
  67948. * @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)
  67949. * @param scene the instance of BABYLON.Scene to append to
  67950. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67951. * @param onProgress a callback with a progress event for each file being loaded
  67952. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67953. * @param pluginExtension the extension used to determine the plugin
  67954. * @returns The loaded plugin
  67955. */
  67956. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67957. if (sceneFilename === void 0) { sceneFilename = ""; }
  67958. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67959. if (onSuccess === void 0) { onSuccess = null; }
  67960. if (onProgress === void 0) { onProgress = null; }
  67961. if (onError === void 0) { onError = null; }
  67962. if (pluginExtension === void 0) { pluginExtension = null; }
  67963. if (!scene) {
  67964. BABYLON.Tools.Error("No scene available to import mesh to");
  67965. return null;
  67966. }
  67967. if (!sceneFilename) {
  67968. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67969. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67970. }
  67971. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67972. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67973. return null;
  67974. }
  67975. var loadingToken = {};
  67976. scene._addPendingData(loadingToken);
  67977. var disposeHandler = function () {
  67978. scene._removePendingData(loadingToken);
  67979. };
  67980. var errorHandler = function (message, exception) {
  67981. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67982. if (onError) {
  67983. onError(scene, errorMessage, exception);
  67984. }
  67985. else {
  67986. BABYLON.Tools.Error(errorMessage);
  67987. // should the exception be thrown?
  67988. }
  67989. disposeHandler();
  67990. };
  67991. var progressHandler = onProgress ? function (event) {
  67992. try {
  67993. onProgress(event);
  67994. }
  67995. catch (e) {
  67996. errorHandler("Error in onProgress callback", e);
  67997. }
  67998. } : undefined;
  67999. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  68000. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  68001. if (onSuccess) {
  68002. try {
  68003. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  68004. }
  68005. catch (e) {
  68006. errorHandler("Error in onSuccess callback", e);
  68007. }
  68008. }
  68009. scene._removePendingData(loadingToken);
  68010. };
  68011. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68012. if (plugin.rewriteRootURL) {
  68013. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  68014. }
  68015. if (sceneFilename === "") {
  68016. if (sceneFilename === "") {
  68017. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68018. }
  68019. }
  68020. if (plugin.importMesh) {
  68021. var syncedPlugin = plugin;
  68022. var meshes = new Array();
  68023. var particleSystems = new Array();
  68024. var skeletons = new Array();
  68025. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  68026. return;
  68027. }
  68028. scene.loadingPluginName = plugin.name;
  68029. successHandler(meshes, particleSystems, skeletons, []);
  68030. }
  68031. else {
  68032. var asyncedPlugin = plugin;
  68033. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  68034. scene.loadingPluginName = plugin.name;
  68035. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  68036. }).catch(function (error) {
  68037. errorHandler(error.message, error);
  68038. });
  68039. }
  68040. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68041. };
  68042. /**
  68043. * Import meshes into a scene
  68044. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68045. * @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)
  68046. * @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)
  68047. * @param scene the instance of BABYLON.Scene to append to
  68048. * @param onProgress a callback with a progress event for each file being loaded
  68049. * @param pluginExtension the extension used to determine the plugin
  68050. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  68051. */
  68052. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68053. if (sceneFilename === void 0) { sceneFilename = ""; }
  68054. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68055. if (onProgress === void 0) { onProgress = null; }
  68056. if (pluginExtension === void 0) { pluginExtension = null; }
  68057. return new Promise(function (resolve, reject) {
  68058. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  68059. resolve({
  68060. meshes: meshes,
  68061. particleSystems: particleSystems,
  68062. skeletons: skeletons,
  68063. animationGroups: animationGroups
  68064. });
  68065. }, onProgress, function (scene, message, exception) {
  68066. reject(exception || new Error(message));
  68067. }, pluginExtension);
  68068. });
  68069. };
  68070. /**
  68071. * Load a scene
  68072. * @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)
  68073. * @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)
  68074. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68075. * @param onSuccess a callback with the scene when import succeeds
  68076. * @param onProgress a callback with a progress event for each file being loaded
  68077. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68078. * @param pluginExtension the extension used to determine the plugin
  68079. * @returns The loaded plugin
  68080. */
  68081. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  68082. if (onSuccess === void 0) { onSuccess = null; }
  68083. if (onProgress === void 0) { onProgress = null; }
  68084. if (onError === void 0) { onError = null; }
  68085. if (pluginExtension === void 0) { pluginExtension = null; }
  68086. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  68087. };
  68088. /**
  68089. * Load a scene
  68090. * @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)
  68091. * @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)
  68092. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68093. * @param onProgress a callback with a progress event for each file being loaded
  68094. * @param pluginExtension the extension used to determine the plugin
  68095. * @returns The loaded scene
  68096. */
  68097. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68098. if (onProgress === void 0) { onProgress = null; }
  68099. if (pluginExtension === void 0) { pluginExtension = null; }
  68100. return new Promise(function (resolve, reject) {
  68101. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68102. resolve(scene);
  68103. }, onProgress, function (scene, message, exception) {
  68104. reject(exception || new Error(message));
  68105. }, pluginExtension);
  68106. });
  68107. };
  68108. /**
  68109. * Append a scene
  68110. * @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)
  68111. * @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)
  68112. * @param scene is the instance of BABYLON.Scene to append to
  68113. * @param onSuccess a callback with the scene when import succeeds
  68114. * @param onProgress a callback with a progress event for each file being loaded
  68115. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68116. * @param pluginExtension the extension used to determine the plugin
  68117. * @returns The loaded plugin
  68118. */
  68119. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68120. if (sceneFilename === void 0) { sceneFilename = ""; }
  68121. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68122. if (onSuccess === void 0) { onSuccess = null; }
  68123. if (onProgress === void 0) { onProgress = null; }
  68124. if (onError === void 0) { onError = null; }
  68125. if (pluginExtension === void 0) { pluginExtension = null; }
  68126. if (!scene) {
  68127. BABYLON.Tools.Error("No scene available to append to");
  68128. return null;
  68129. }
  68130. if (!sceneFilename) {
  68131. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68132. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68133. }
  68134. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68135. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68136. return null;
  68137. }
  68138. if (SceneLoader.ShowLoadingScreen) {
  68139. scene.getEngine().displayLoadingUI();
  68140. }
  68141. var loadingToken = {};
  68142. scene._addPendingData(loadingToken);
  68143. var disposeHandler = function () {
  68144. scene._removePendingData(loadingToken);
  68145. scene.getEngine().hideLoadingUI();
  68146. };
  68147. var errorHandler = function (message, exception) {
  68148. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68149. if (onError) {
  68150. onError(scene, errorMessage, exception);
  68151. }
  68152. else {
  68153. BABYLON.Tools.Error(errorMessage);
  68154. // should the exception be thrown?
  68155. }
  68156. disposeHandler();
  68157. };
  68158. var progressHandler = onProgress ? function (event) {
  68159. try {
  68160. onProgress(event);
  68161. }
  68162. catch (e) {
  68163. errorHandler("Error in onProgress callback", e);
  68164. }
  68165. } : undefined;
  68166. var successHandler = function () {
  68167. if (onSuccess) {
  68168. try {
  68169. onSuccess(scene);
  68170. }
  68171. catch (e) {
  68172. errorHandler("Error in onSuccess callback", e);
  68173. }
  68174. }
  68175. scene._removePendingData(loadingToken);
  68176. };
  68177. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68178. if (sceneFilename === "") {
  68179. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68180. }
  68181. if (plugin.load) {
  68182. var syncedPlugin = plugin;
  68183. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68184. return;
  68185. }
  68186. scene.loadingPluginName = plugin.name;
  68187. successHandler();
  68188. }
  68189. else {
  68190. var asyncedPlugin = plugin;
  68191. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68192. scene.loadingPluginName = plugin.name;
  68193. successHandler();
  68194. }).catch(function (error) {
  68195. errorHandler(error.message, error);
  68196. });
  68197. }
  68198. if (SceneLoader.ShowLoadingScreen) {
  68199. scene.executeWhenReady(function () {
  68200. scene.getEngine().hideLoadingUI();
  68201. });
  68202. }
  68203. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68204. };
  68205. /**
  68206. * Append a scene
  68207. * @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)
  68208. * @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)
  68209. * @param scene is the instance of BABYLON.Scene to append to
  68210. * @param onProgress a callback with a progress event for each file being loaded
  68211. * @param pluginExtension the extension used to determine the plugin
  68212. * @returns The given scene
  68213. */
  68214. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68215. if (sceneFilename === void 0) { sceneFilename = ""; }
  68216. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68217. if (onProgress === void 0) { onProgress = null; }
  68218. if (pluginExtension === void 0) { pluginExtension = null; }
  68219. return new Promise(function (resolve, reject) {
  68220. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68221. resolve(scene);
  68222. }, onProgress, function (scene, message, exception) {
  68223. reject(exception || new Error(message));
  68224. }, pluginExtension);
  68225. });
  68226. };
  68227. /**
  68228. * Load a scene into an asset container
  68229. * @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)
  68230. * @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)
  68231. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68232. * @param onSuccess a callback with the scene when import succeeds
  68233. * @param onProgress a callback with a progress event for each file being loaded
  68234. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68235. * @param pluginExtension the extension used to determine the plugin
  68236. * @returns The loaded plugin
  68237. */
  68238. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68239. if (sceneFilename === void 0) { sceneFilename = ""; }
  68240. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68241. if (onSuccess === void 0) { onSuccess = null; }
  68242. if (onProgress === void 0) { onProgress = null; }
  68243. if (onError === void 0) { onError = null; }
  68244. if (pluginExtension === void 0) { pluginExtension = null; }
  68245. if (!scene) {
  68246. BABYLON.Tools.Error("No scene available to load asset container to");
  68247. return null;
  68248. }
  68249. if (!sceneFilename) {
  68250. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68251. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68252. }
  68253. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68254. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68255. return null;
  68256. }
  68257. var loadingToken = {};
  68258. scene._addPendingData(loadingToken);
  68259. var disposeHandler = function () {
  68260. scene._removePendingData(loadingToken);
  68261. };
  68262. var errorHandler = function (message, exception) {
  68263. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68264. if (onError) {
  68265. onError(scene, errorMessage, exception);
  68266. }
  68267. else {
  68268. BABYLON.Tools.Error(errorMessage);
  68269. // should the exception be thrown?
  68270. }
  68271. disposeHandler();
  68272. };
  68273. var progressHandler = onProgress ? function (event) {
  68274. try {
  68275. onProgress(event);
  68276. }
  68277. catch (e) {
  68278. errorHandler("Error in onProgress callback", e);
  68279. }
  68280. } : undefined;
  68281. var successHandler = function (assets) {
  68282. if (onSuccess) {
  68283. try {
  68284. onSuccess(assets);
  68285. }
  68286. catch (e) {
  68287. errorHandler("Error in onSuccess callback", e);
  68288. }
  68289. }
  68290. scene._removePendingData(loadingToken);
  68291. };
  68292. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68293. if (plugin.loadAssetContainer) {
  68294. var syncedPlugin = plugin;
  68295. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68296. if (!assetContainer) {
  68297. return;
  68298. }
  68299. scene.loadingPluginName = plugin.name;
  68300. successHandler(assetContainer);
  68301. }
  68302. else if (plugin.loadAssetContainerAsync) {
  68303. var asyncedPlugin = plugin;
  68304. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68305. scene.loadingPluginName = plugin.name;
  68306. successHandler(assetContainer);
  68307. }).catch(function (error) {
  68308. errorHandler(error.message, error);
  68309. });
  68310. }
  68311. else {
  68312. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68313. }
  68314. if (SceneLoader.ShowLoadingScreen) {
  68315. scene.executeWhenReady(function () {
  68316. scene.getEngine().hideLoadingUI();
  68317. });
  68318. }
  68319. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68320. };
  68321. /**
  68322. * Load a scene into an asset container
  68323. * @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)
  68324. * @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)
  68325. * @param scene is the instance of BABYLON.Scene to append to
  68326. * @param onProgress a callback with a progress event for each file being loaded
  68327. * @param pluginExtension the extension used to determine the plugin
  68328. * @returns The loaded asset container
  68329. */
  68330. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68331. if (sceneFilename === void 0) { sceneFilename = ""; }
  68332. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68333. if (onProgress === void 0) { onProgress = null; }
  68334. if (pluginExtension === void 0) { pluginExtension = null; }
  68335. return new Promise(function (resolve, reject) {
  68336. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68337. resolve(assetContainer);
  68338. }, onProgress, function (scene, message, exception) {
  68339. reject(exception || new Error(message));
  68340. }, pluginExtension);
  68341. });
  68342. };
  68343. // Flags
  68344. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68345. SceneLoader._ShowLoadingScreen = true;
  68346. SceneLoader._CleanBoneMatrixWeights = false;
  68347. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68348. // Members
  68349. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68350. SceneLoader._registeredPlugins = {};
  68351. return SceneLoader;
  68352. }());
  68353. BABYLON.SceneLoader = SceneLoader;
  68354. ;
  68355. })(BABYLON || (BABYLON = {}));
  68356. //# sourceMappingURL=babylon.sceneLoader.js.map
  68357. var BABYLON;
  68358. (function (BABYLON) {
  68359. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68360. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68361. var parsedMaterial = parsedData.materials[index];
  68362. if (parsedMaterial.id === id) {
  68363. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68364. }
  68365. }
  68366. return null;
  68367. };
  68368. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68369. for (var i in names) {
  68370. if (mesh.name === names[i]) {
  68371. hierarchyIds.push(mesh.id);
  68372. return true;
  68373. }
  68374. }
  68375. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68376. hierarchyIds.push(mesh.id);
  68377. return true;
  68378. }
  68379. return false;
  68380. };
  68381. var logOperation = function (operation, producer) {
  68382. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68383. };
  68384. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68385. if (addToScene === void 0) { addToScene = false; }
  68386. var container = new BABYLON.AssetContainer(scene);
  68387. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68388. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68389. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68390. // and avoid problems with multiple concurrent .babylon loads.
  68391. var log = "importScene has failed JSON parse";
  68392. try {
  68393. var parsedData = JSON.parse(data);
  68394. log = "";
  68395. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68396. var index;
  68397. var cache;
  68398. // Lights
  68399. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68400. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68401. var parsedLight = parsedData.lights[index];
  68402. var light = BABYLON.Light.Parse(parsedLight, scene);
  68403. if (light) {
  68404. container.lights.push(light);
  68405. log += (index === 0 ? "\n\tLights:" : "");
  68406. log += "\n\t\t" + light.toString(fullDetails);
  68407. }
  68408. }
  68409. }
  68410. // Animations
  68411. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68412. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68413. var parsedAnimation = parsedData.animations[index];
  68414. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68415. scene.animations.push(animation);
  68416. container.animations.push(animation);
  68417. log += (index === 0 ? "\n\tAnimations:" : "");
  68418. log += "\n\t\t" + animation.toString(fullDetails);
  68419. }
  68420. }
  68421. // Materials
  68422. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68423. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68424. var parsedMaterial = parsedData.materials[index];
  68425. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68426. container.materials.push(mat);
  68427. log += (index === 0 ? "\n\tMaterials:" : "");
  68428. log += "\n\t\t" + mat.toString(fullDetails);
  68429. }
  68430. }
  68431. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68432. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68433. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68434. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68435. container.multiMaterials.push(mmat);
  68436. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68437. log += "\n\t\t" + mmat.toString(fullDetails);
  68438. }
  68439. }
  68440. // Morph targets
  68441. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68442. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68443. var managerData = _a[_i];
  68444. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68445. }
  68446. }
  68447. // Skeletons
  68448. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68449. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68450. var parsedSkeleton = parsedData.skeletons[index];
  68451. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68452. container.skeletons.push(skeleton);
  68453. log += (index === 0 ? "\n\tSkeletons:" : "");
  68454. log += "\n\t\t" + skeleton.toString(fullDetails);
  68455. }
  68456. }
  68457. // Geometries
  68458. var geometries = parsedData.geometries;
  68459. if (geometries !== undefined && geometries !== null) {
  68460. var addedGeometry = new Array();
  68461. // Boxes
  68462. var boxes = geometries.boxes;
  68463. if (boxes !== undefined && boxes !== null) {
  68464. for (index = 0, cache = boxes.length; index < cache; index++) {
  68465. var parsedBox = boxes[index];
  68466. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68467. }
  68468. }
  68469. // Spheres
  68470. var spheres = geometries.spheres;
  68471. if (spheres !== undefined && spheres !== null) {
  68472. for (index = 0, cache = spheres.length; index < cache; index++) {
  68473. var parsedSphere = spheres[index];
  68474. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68475. }
  68476. }
  68477. // Cylinders
  68478. var cylinders = geometries.cylinders;
  68479. if (cylinders !== undefined && cylinders !== null) {
  68480. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68481. var parsedCylinder = cylinders[index];
  68482. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68483. }
  68484. }
  68485. // Toruses
  68486. var toruses = geometries.toruses;
  68487. if (toruses !== undefined && toruses !== null) {
  68488. for (index = 0, cache = toruses.length; index < cache; index++) {
  68489. var parsedTorus = toruses[index];
  68490. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68491. }
  68492. }
  68493. // Grounds
  68494. var grounds = geometries.grounds;
  68495. if (grounds !== undefined && grounds !== null) {
  68496. for (index = 0, cache = grounds.length; index < cache; index++) {
  68497. var parsedGround = grounds[index];
  68498. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68499. }
  68500. }
  68501. // Planes
  68502. var planes = geometries.planes;
  68503. if (planes !== undefined && planes !== null) {
  68504. for (index = 0, cache = planes.length; index < cache; index++) {
  68505. var parsedPlane = planes[index];
  68506. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68507. }
  68508. }
  68509. // TorusKnots
  68510. var torusKnots = geometries.torusKnots;
  68511. if (torusKnots !== undefined && torusKnots !== null) {
  68512. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68513. var parsedTorusKnot = torusKnots[index];
  68514. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68515. }
  68516. }
  68517. // VertexData
  68518. var vertexData = geometries.vertexData;
  68519. if (vertexData !== undefined && vertexData !== null) {
  68520. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68521. var parsedVertexData = vertexData[index];
  68522. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68523. }
  68524. }
  68525. addedGeometry.forEach(function (g) {
  68526. if (g) {
  68527. container.geometries.push(g);
  68528. }
  68529. });
  68530. }
  68531. // Transform nodes
  68532. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68533. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68534. var parsedTransformNode = parsedData.transformNodes[index];
  68535. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68536. container.transformNodes.push(node);
  68537. }
  68538. }
  68539. // Meshes
  68540. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68541. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68542. var parsedMesh = parsedData.meshes[index];
  68543. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68544. container.meshes.push(mesh);
  68545. log += (index === 0 ? "\n\tMeshes:" : "");
  68546. log += "\n\t\t" + mesh.toString(fullDetails);
  68547. }
  68548. }
  68549. // Cameras
  68550. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68551. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68552. var parsedCamera = parsedData.cameras[index];
  68553. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68554. container.cameras.push(camera);
  68555. log += (index === 0 ? "\n\tCameras:" : "");
  68556. log += "\n\t\t" + camera.toString(fullDetails);
  68557. }
  68558. }
  68559. // Browsing all the graph to connect the dots
  68560. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68561. var camera = scene.cameras[index];
  68562. if (camera._waitingParentId) {
  68563. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68564. camera._waitingParentId = null;
  68565. }
  68566. }
  68567. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68568. var light_1 = scene.lights[index];
  68569. if (light_1 && light_1._waitingParentId) {
  68570. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68571. light_1._waitingParentId = null;
  68572. }
  68573. }
  68574. // Sounds
  68575. // TODO: add sound
  68576. var loadedSounds = [];
  68577. var loadedSound;
  68578. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68579. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68580. var parsedSound = parsedData.sounds[index];
  68581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68582. if (!parsedSound.url)
  68583. parsedSound.url = parsedSound.name;
  68584. if (!loadedSounds[parsedSound.url]) {
  68585. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68586. loadedSounds[parsedSound.url] = loadedSound;
  68587. container.sounds.push(loadedSound);
  68588. }
  68589. else {
  68590. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68591. }
  68592. }
  68593. else {
  68594. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68595. }
  68596. }
  68597. }
  68598. loadedSounds = [];
  68599. // Connect parents & children and parse actions
  68600. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68601. var transformNode = scene.transformNodes[index];
  68602. if (transformNode._waitingParentId) {
  68603. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68604. transformNode._waitingParentId = null;
  68605. }
  68606. }
  68607. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68608. var mesh = scene.meshes[index];
  68609. if (mesh._waitingParentId) {
  68610. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68611. mesh._waitingParentId = null;
  68612. }
  68613. if (mesh._waitingActions) {
  68614. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68615. mesh._waitingActions = null;
  68616. }
  68617. }
  68618. // freeze world matrix application
  68619. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68620. var currentMesh = scene.meshes[index];
  68621. if (currentMesh._waitingFreezeWorldMatrix) {
  68622. currentMesh.freezeWorldMatrix();
  68623. currentMesh._waitingFreezeWorldMatrix = null;
  68624. }
  68625. else {
  68626. currentMesh.computeWorldMatrix(true);
  68627. }
  68628. }
  68629. // Particles Systems
  68630. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68631. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68632. var parsedParticleSystem = parsedData.particleSystems[index];
  68633. if (parsedParticleSystem.activeParticleCount) {
  68634. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68635. container.particleSystems.push(ps);
  68636. }
  68637. else {
  68638. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68639. container.particleSystems.push(ps);
  68640. }
  68641. }
  68642. }
  68643. // Shadows
  68644. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68645. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68646. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68647. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68648. // SG would be available on their associated lights
  68649. }
  68650. }
  68651. // Lights exclusions / inclusions
  68652. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68653. var light_2 = scene.lights[index];
  68654. // Excluded check
  68655. if (light_2._excludedMeshesIds.length > 0) {
  68656. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68657. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68658. if (excludedMesh) {
  68659. light_2.excludedMeshes.push(excludedMesh);
  68660. }
  68661. }
  68662. light_2._excludedMeshesIds = [];
  68663. }
  68664. // Included check
  68665. if (light_2._includedOnlyMeshesIds.length > 0) {
  68666. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68667. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68668. if (includedOnlyMesh) {
  68669. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68670. }
  68671. }
  68672. light_2._includedOnlyMeshesIds = [];
  68673. }
  68674. }
  68675. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68676. // Actions (scene)
  68677. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68678. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68679. }
  68680. if (!addToScene) {
  68681. container.removeAllFromScene();
  68682. }
  68683. }
  68684. catch (err) {
  68685. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68686. if (onError) {
  68687. onError(msg, err);
  68688. }
  68689. else {
  68690. BABYLON.Tools.Log(msg);
  68691. throw err;
  68692. }
  68693. }
  68694. finally {
  68695. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68696. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68697. }
  68698. }
  68699. return container;
  68700. };
  68701. BABYLON.SceneLoader.RegisterPlugin({
  68702. name: "babylon.js",
  68703. extensions: ".babylon",
  68704. canDirectLoad: function (data) {
  68705. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68706. return true;
  68707. }
  68708. return false;
  68709. },
  68710. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68711. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68712. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68713. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68714. // and avoid problems with multiple concurrent .babylon loads.
  68715. var log = "importMesh has failed JSON parse";
  68716. try {
  68717. var parsedData = JSON.parse(data);
  68718. log = "";
  68719. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68720. if (!meshesNames) {
  68721. meshesNames = null;
  68722. }
  68723. else if (!Array.isArray(meshesNames)) {
  68724. meshesNames = [meshesNames];
  68725. }
  68726. var hierarchyIds = new Array();
  68727. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68728. var loadedSkeletonsIds = [];
  68729. var loadedMaterialsIds = [];
  68730. var index;
  68731. var cache;
  68732. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68733. var parsedMesh = parsedData.meshes[index];
  68734. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68735. if (meshesNames !== null) {
  68736. // Remove found mesh name from list.
  68737. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68738. }
  68739. //Geometry?
  68740. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68741. //does the file contain geometries?
  68742. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68743. //find the correct geometry and add it to the scene
  68744. var found = false;
  68745. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68746. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68747. return;
  68748. }
  68749. else {
  68750. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68751. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68752. switch (geometryType) {
  68753. case "boxes":
  68754. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68755. break;
  68756. case "spheres":
  68757. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68758. break;
  68759. case "cylinders":
  68760. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68761. break;
  68762. case "toruses":
  68763. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68764. break;
  68765. case "grounds":
  68766. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68767. break;
  68768. case "planes":
  68769. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68770. break;
  68771. case "torusKnots":
  68772. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68773. break;
  68774. case "vertexData":
  68775. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68776. break;
  68777. }
  68778. found = true;
  68779. }
  68780. });
  68781. }
  68782. });
  68783. if (found === false) {
  68784. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68785. }
  68786. }
  68787. }
  68788. // Material ?
  68789. if (parsedMesh.materialId) {
  68790. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68791. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68792. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68793. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68794. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68795. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68796. var subMatId = parsedMultiMaterial.materials[matIndex];
  68797. loadedMaterialsIds.push(subMatId);
  68798. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68799. if (mat) {
  68800. log += "\n\tMaterial " + mat.toString(fullDetails);
  68801. }
  68802. }
  68803. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68804. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68805. if (mmat) {
  68806. materialFound = true;
  68807. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68808. }
  68809. break;
  68810. }
  68811. }
  68812. }
  68813. if (materialFound === false) {
  68814. loadedMaterialsIds.push(parsedMesh.materialId);
  68815. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68816. if (!mat) {
  68817. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68818. }
  68819. else {
  68820. log += "\n\tMaterial " + mat.toString(fullDetails);
  68821. }
  68822. }
  68823. }
  68824. // Skeleton ?
  68825. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68826. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68827. if (skeletonAlreadyLoaded === false) {
  68828. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68829. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68830. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68831. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68832. skeletons.push(skeleton);
  68833. loadedSkeletonsIds.push(parsedSkeleton.id);
  68834. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68835. }
  68836. }
  68837. }
  68838. }
  68839. // Morph targets ?
  68840. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68841. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68842. var managerData = _a[_i];
  68843. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68844. }
  68845. }
  68846. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68847. meshes.push(mesh);
  68848. log += "\n\tMesh " + mesh.toString(fullDetails);
  68849. }
  68850. }
  68851. // Connecting parents
  68852. var currentMesh;
  68853. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68854. currentMesh = scene.meshes[index];
  68855. if (currentMesh._waitingParentId) {
  68856. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68857. currentMesh._waitingParentId = null;
  68858. }
  68859. }
  68860. // freeze and compute world matrix application
  68861. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68862. currentMesh = scene.meshes[index];
  68863. if (currentMesh._waitingFreezeWorldMatrix) {
  68864. currentMesh.freezeWorldMatrix();
  68865. currentMesh._waitingFreezeWorldMatrix = null;
  68866. }
  68867. else {
  68868. currentMesh.computeWorldMatrix(true);
  68869. }
  68870. }
  68871. }
  68872. // Particles
  68873. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68874. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68875. var parsedParticleSystem = parsedData.particleSystems[index];
  68876. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68877. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68878. }
  68879. }
  68880. }
  68881. return true;
  68882. }
  68883. catch (err) {
  68884. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68885. if (onError) {
  68886. onError(msg, err);
  68887. }
  68888. else {
  68889. BABYLON.Tools.Log(msg);
  68890. throw err;
  68891. }
  68892. }
  68893. finally {
  68894. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68895. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68896. }
  68897. }
  68898. return false;
  68899. },
  68900. load: function (scene, data, rootUrl, onError) {
  68901. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68902. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68903. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68904. // and avoid problems with multiple concurrent .babylon loads.
  68905. var log = "importScene has failed JSON parse";
  68906. try {
  68907. var parsedData = JSON.parse(data);
  68908. log = "";
  68909. // Scene
  68910. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68911. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68912. }
  68913. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68914. scene.autoClear = parsedData.autoClear;
  68915. }
  68916. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68917. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68918. }
  68919. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68920. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68921. }
  68922. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68923. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68924. }
  68925. // Fog
  68926. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68927. scene.fogMode = parsedData.fogMode;
  68928. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68929. scene.fogStart = parsedData.fogStart;
  68930. scene.fogEnd = parsedData.fogEnd;
  68931. scene.fogDensity = parsedData.fogDensity;
  68932. log += "\tFog mode for scene: ";
  68933. switch (scene.fogMode) {
  68934. // getters not compiling, so using hardcoded
  68935. case 1:
  68936. log += "exp\n";
  68937. break;
  68938. case 2:
  68939. log += "exp2\n";
  68940. break;
  68941. case 3:
  68942. log += "linear\n";
  68943. break;
  68944. }
  68945. }
  68946. //Physics
  68947. if (parsedData.physicsEnabled) {
  68948. var physicsPlugin;
  68949. if (parsedData.physicsEngine === "cannon") {
  68950. physicsPlugin = new BABYLON.CannonJSPlugin();
  68951. }
  68952. else if (parsedData.physicsEngine === "oimo") {
  68953. physicsPlugin = new BABYLON.OimoJSPlugin();
  68954. }
  68955. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68956. //else - default engine, which is currently oimo
  68957. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68958. scene.enablePhysics(physicsGravity, physicsPlugin);
  68959. }
  68960. // Metadata
  68961. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68962. scene.metadata = parsedData.metadata;
  68963. }
  68964. //collisions, if defined. otherwise, default is true
  68965. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68966. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68967. }
  68968. scene.workerCollisions = !!parsedData.workerCollisions;
  68969. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68970. if (!container) {
  68971. return false;
  68972. }
  68973. if (parsedData.autoAnimate) {
  68974. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68975. }
  68976. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68977. scene.setActiveCameraByID(parsedData.activeCameraID);
  68978. }
  68979. // Environment texture
  68980. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68981. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68982. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68983. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68984. if (parsedData.environmentTextureRotationY) {
  68985. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68986. }
  68987. scene.environmentTexture = hdrTexture;
  68988. }
  68989. else {
  68990. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68991. if (parsedData.environmentTextureRotationY) {
  68992. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68993. }
  68994. scene.environmentTexture = cubeTexture;
  68995. }
  68996. if (parsedData.createDefaultSkybox === true) {
  68997. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68998. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68999. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  69000. }
  69001. }
  69002. // Finish
  69003. return true;
  69004. }
  69005. catch (err) {
  69006. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  69007. if (onError) {
  69008. onError(msg, err);
  69009. }
  69010. else {
  69011. BABYLON.Tools.Log(msg);
  69012. throw err;
  69013. }
  69014. }
  69015. finally {
  69016. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69017. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69018. }
  69019. }
  69020. return false;
  69021. },
  69022. loadAssetContainer: function (scene, data, rootUrl, onError) {
  69023. var container = loadAssetContainer(scene, data, rootUrl, onError);
  69024. return container;
  69025. }
  69026. });
  69027. })(BABYLON || (BABYLON = {}));
  69028. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  69029. var BABYLON;
  69030. (function (BABYLON) {
  69031. var FilesInput = /** @class */ (function () {
  69032. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  69033. this.onProcessFileCallback = function () { return true; };
  69034. this._engine = engine;
  69035. this._currentScene = scene;
  69036. this._sceneLoadedCallback = sceneLoadedCallback;
  69037. this._progressCallback = progressCallback;
  69038. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  69039. this._textureLoadingCallback = textureLoadingCallback;
  69040. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  69041. this._onReloadCallback = onReloadCallback;
  69042. this._errorCallback = errorCallback;
  69043. }
  69044. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  69045. var _this = this;
  69046. if (elementToMonitor) {
  69047. this._elementToMonitor = elementToMonitor;
  69048. this._dragEnterHandler = function (e) { _this.drag(e); };
  69049. this._dragOverHandler = function (e) { _this.drag(e); };
  69050. this._dropHandler = function (e) { _this.drop(e); };
  69051. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  69052. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  69053. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  69054. }
  69055. };
  69056. FilesInput.prototype.dispose = function () {
  69057. if (!this._elementToMonitor) {
  69058. return;
  69059. }
  69060. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  69061. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  69062. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  69063. };
  69064. FilesInput.prototype.renderFunction = function () {
  69065. if (this._additionalRenderLoopLogicCallback) {
  69066. this._additionalRenderLoopLogicCallback();
  69067. }
  69068. if (this._currentScene) {
  69069. if (this._textureLoadingCallback) {
  69070. var remaining = this._currentScene.getWaitingItemsCount();
  69071. if (remaining > 0) {
  69072. this._textureLoadingCallback(remaining);
  69073. }
  69074. }
  69075. this._currentScene.render();
  69076. }
  69077. };
  69078. FilesInput.prototype.drag = function (e) {
  69079. e.stopPropagation();
  69080. e.preventDefault();
  69081. };
  69082. FilesInput.prototype.drop = function (eventDrop) {
  69083. eventDrop.stopPropagation();
  69084. eventDrop.preventDefault();
  69085. this.loadFiles(eventDrop);
  69086. };
  69087. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69088. var _this = this;
  69089. var reader = folder.createReader();
  69090. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69091. reader.readEntries(function (entries) {
  69092. remaining.count += entries.length;
  69093. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69094. var entry = entries_1[_i];
  69095. if (entry.isFile) {
  69096. entry.file(function (file) {
  69097. file.correctName = relativePath + file.name;
  69098. files.push(file);
  69099. if (--remaining.count === 0) {
  69100. callback();
  69101. }
  69102. });
  69103. }
  69104. else if (entry.isDirectory) {
  69105. _this._traverseFolder(entry, files, remaining, callback);
  69106. }
  69107. }
  69108. if (--remaining.count) {
  69109. callback();
  69110. }
  69111. });
  69112. };
  69113. FilesInput.prototype._processFiles = function (files) {
  69114. for (var i = 0; i < files.length; i++) {
  69115. var name = files[i].correctName.toLowerCase();
  69116. var extension = name.split('.').pop();
  69117. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69118. continue;
  69119. }
  69120. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69121. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69122. this._sceneFileToLoad = files[i];
  69123. }
  69124. else {
  69125. FilesInput.FilesToLoad[name] = files[i];
  69126. }
  69127. }
  69128. };
  69129. FilesInput.prototype.loadFiles = function (event) {
  69130. var _this = this;
  69131. if (this._startingProcessingFilesCallback)
  69132. this._startingProcessingFilesCallback();
  69133. // Handling data transfer via drag'n'drop
  69134. if (event && event.dataTransfer && event.dataTransfer.files) {
  69135. this._filesToLoad = event.dataTransfer.files;
  69136. }
  69137. // Handling files from input files
  69138. if (event && event.target && event.target.files) {
  69139. this._filesToLoad = event.target.files;
  69140. }
  69141. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69142. var files_1 = new Array();
  69143. var folders = [];
  69144. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69145. for (var i = 0; i < this._filesToLoad.length; i++) {
  69146. var fileToLoad = this._filesToLoad[i];
  69147. var name_1 = fileToLoad.name.toLowerCase();
  69148. var entry = void 0;
  69149. fileToLoad.correctName = name_1;
  69150. if (items) {
  69151. var item = items[i];
  69152. if (item.getAsEntry) {
  69153. entry = item.getAsEntry();
  69154. }
  69155. else if (item.webkitGetAsEntry) {
  69156. entry = item.webkitGetAsEntry();
  69157. }
  69158. }
  69159. if (!entry) {
  69160. files_1.push(fileToLoad);
  69161. }
  69162. else {
  69163. if (entry.isDirectory) {
  69164. folders.push(entry);
  69165. }
  69166. else {
  69167. files_1.push(fileToLoad);
  69168. }
  69169. }
  69170. }
  69171. if (folders.length === 0) {
  69172. this._processFiles(files_1);
  69173. this._processReload();
  69174. }
  69175. else {
  69176. var remaining = { count: folders.length };
  69177. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69178. var folder = folders_1[_i];
  69179. this._traverseFolder(folder, files_1, remaining, function () {
  69180. _this._processFiles(files_1);
  69181. if (remaining.count === 0) {
  69182. _this._processReload();
  69183. }
  69184. });
  69185. }
  69186. }
  69187. }
  69188. };
  69189. FilesInput.prototype._processReload = function () {
  69190. if (this._onReloadCallback) {
  69191. this._onReloadCallback(this._sceneFileToLoad);
  69192. }
  69193. else {
  69194. this.reload();
  69195. }
  69196. };
  69197. FilesInput.prototype.reload = function () {
  69198. var _this = this;
  69199. // If a scene file has been provided
  69200. if (this._sceneFileToLoad) {
  69201. if (this._currentScene) {
  69202. if (BABYLON.Tools.errorsCount > 0) {
  69203. BABYLON.Tools.ClearLogCache();
  69204. }
  69205. this._engine.stopRenderLoop();
  69206. }
  69207. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69208. if (_this._progressCallback) {
  69209. _this._progressCallback(progress);
  69210. }
  69211. }).then(function (scene) {
  69212. if (_this._currentScene) {
  69213. _this._currentScene.dispose();
  69214. }
  69215. _this._currentScene = scene;
  69216. if (_this._sceneLoadedCallback) {
  69217. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69218. }
  69219. // Wait for textures and shaders to be ready
  69220. _this._currentScene.executeWhenReady(function () {
  69221. _this._engine.runRenderLoop(function () {
  69222. _this.renderFunction();
  69223. });
  69224. });
  69225. }).catch(function (error) {
  69226. if (_this._errorCallback) {
  69227. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69228. }
  69229. });
  69230. }
  69231. else {
  69232. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69233. }
  69234. };
  69235. FilesInput.FilesToLoad = {};
  69236. return FilesInput;
  69237. }());
  69238. BABYLON.FilesInput = FilesInput;
  69239. })(BABYLON || (BABYLON = {}));
  69240. //# sourceMappingURL=babylon.filesInput.js.map
  69241. var BABYLON;
  69242. (function (BABYLON) {
  69243. /**
  69244. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69245. * The underlying implementation relies on an associative array to ensure the best performances.
  69246. * The value can be anything including 'null' but except 'undefined'
  69247. */
  69248. var StringDictionary = /** @class */ (function () {
  69249. function StringDictionary() {
  69250. this._count = 0;
  69251. this._data = {};
  69252. }
  69253. /**
  69254. * This will clear this dictionary and copy the content from the 'source' one.
  69255. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69256. * @param source the dictionary to take the content from and copy to this dictionary
  69257. */
  69258. StringDictionary.prototype.copyFrom = function (source) {
  69259. var _this = this;
  69260. this.clear();
  69261. source.forEach(function (t, v) { return _this.add(t, v); });
  69262. };
  69263. /**
  69264. * Get a value based from its key
  69265. * @param key the given key to get the matching value from
  69266. * @return the value if found, otherwise undefined is returned
  69267. */
  69268. StringDictionary.prototype.get = function (key) {
  69269. var val = this._data[key];
  69270. if (val !== undefined) {
  69271. return val;
  69272. }
  69273. return undefined;
  69274. };
  69275. /**
  69276. * Get a value from its key or add it if it doesn't exist.
  69277. * This method will ensure you that a given key/data will be present in the dictionary.
  69278. * @param key the given key to get the matching value from
  69279. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69280. * The factory will only be invoked if there's no data for the given key.
  69281. * @return the value corresponding to the key.
  69282. */
  69283. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69284. var val = this.get(key);
  69285. if (val !== undefined) {
  69286. return val;
  69287. }
  69288. val = factory(key);
  69289. if (val) {
  69290. this.add(key, val);
  69291. }
  69292. return val;
  69293. };
  69294. /**
  69295. * Get a value from its key if present in the dictionary otherwise add it
  69296. * @param key the key to get the value from
  69297. * @param val if there's no such key/value pair in the dictionary add it with this value
  69298. * @return the value corresponding to the key
  69299. */
  69300. StringDictionary.prototype.getOrAdd = function (key, val) {
  69301. var curVal = this.get(key);
  69302. if (curVal !== undefined) {
  69303. return curVal;
  69304. }
  69305. this.add(key, val);
  69306. return val;
  69307. };
  69308. /**
  69309. * Check if there's a given key in the dictionary
  69310. * @param key the key to check for
  69311. * @return true if the key is present, false otherwise
  69312. */
  69313. StringDictionary.prototype.contains = function (key) {
  69314. return this._data[key] !== undefined;
  69315. };
  69316. /**
  69317. * Add a new key and its corresponding value
  69318. * @param key the key to add
  69319. * @param value the value corresponding to the key
  69320. * @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
  69321. */
  69322. StringDictionary.prototype.add = function (key, value) {
  69323. if (this._data[key] !== undefined) {
  69324. return false;
  69325. }
  69326. this._data[key] = value;
  69327. ++this._count;
  69328. return true;
  69329. };
  69330. StringDictionary.prototype.set = function (key, value) {
  69331. if (this._data[key] === undefined) {
  69332. return false;
  69333. }
  69334. this._data[key] = value;
  69335. return true;
  69336. };
  69337. /**
  69338. * Get the element of the given key and remove it from the dictionary
  69339. * @param key
  69340. */
  69341. StringDictionary.prototype.getAndRemove = function (key) {
  69342. var val = this.get(key);
  69343. if (val !== undefined) {
  69344. delete this._data[key];
  69345. --this._count;
  69346. return val;
  69347. }
  69348. return null;
  69349. };
  69350. /**
  69351. * Remove a key/value from the dictionary.
  69352. * @param key the key to remove
  69353. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69354. */
  69355. StringDictionary.prototype.remove = function (key) {
  69356. if (this.contains(key)) {
  69357. delete this._data[key];
  69358. --this._count;
  69359. return true;
  69360. }
  69361. return false;
  69362. };
  69363. /**
  69364. * Clear the whole content of the dictionary
  69365. */
  69366. StringDictionary.prototype.clear = function () {
  69367. this._data = {};
  69368. this._count = 0;
  69369. };
  69370. Object.defineProperty(StringDictionary.prototype, "count", {
  69371. get: function () {
  69372. return this._count;
  69373. },
  69374. enumerable: true,
  69375. configurable: true
  69376. });
  69377. /**
  69378. * Execute a callback on each key/val of the dictionary.
  69379. * Note that you can remove any element in this dictionary in the callback implementation
  69380. * @param callback the callback to execute on a given key/value pair
  69381. */
  69382. StringDictionary.prototype.forEach = function (callback) {
  69383. for (var cur in this._data) {
  69384. var val = this._data[cur];
  69385. callback(cur, val);
  69386. }
  69387. };
  69388. /**
  69389. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69390. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69391. * Note that you can remove any element in this dictionary in the callback implementation
  69392. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69393. */
  69394. StringDictionary.prototype.first = function (callback) {
  69395. for (var cur in this._data) {
  69396. var val = this._data[cur];
  69397. var res = callback(cur, val);
  69398. if (res) {
  69399. return res;
  69400. }
  69401. }
  69402. return null;
  69403. };
  69404. return StringDictionary;
  69405. }());
  69406. BABYLON.StringDictionary = StringDictionary;
  69407. })(BABYLON || (BABYLON = {}));
  69408. //# sourceMappingURL=babylon.stringDictionary.js.map
  69409. var BABYLON;
  69410. (function (BABYLON) {
  69411. var Tags = /** @class */ (function () {
  69412. function Tags() {
  69413. }
  69414. Tags.EnableFor = function (obj) {
  69415. obj._tags = obj._tags || {};
  69416. obj.hasTags = function () {
  69417. return Tags.HasTags(obj);
  69418. };
  69419. obj.addTags = function (tagsString) {
  69420. return Tags.AddTagsTo(obj, tagsString);
  69421. };
  69422. obj.removeTags = function (tagsString) {
  69423. return Tags.RemoveTagsFrom(obj, tagsString);
  69424. };
  69425. obj.matchesTagsQuery = function (tagsQuery) {
  69426. return Tags.MatchesQuery(obj, tagsQuery);
  69427. };
  69428. };
  69429. Tags.DisableFor = function (obj) {
  69430. delete obj._tags;
  69431. delete obj.hasTags;
  69432. delete obj.addTags;
  69433. delete obj.removeTags;
  69434. delete obj.matchesTagsQuery;
  69435. };
  69436. Tags.HasTags = function (obj) {
  69437. if (!obj._tags) {
  69438. return false;
  69439. }
  69440. return !BABYLON.Tools.IsEmpty(obj._tags);
  69441. };
  69442. Tags.GetTags = function (obj, asString) {
  69443. if (asString === void 0) { asString = true; }
  69444. if (!obj._tags) {
  69445. return null;
  69446. }
  69447. if (asString) {
  69448. var tagsArray = [];
  69449. for (var tag in obj._tags) {
  69450. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69451. tagsArray.push(tag);
  69452. }
  69453. }
  69454. return tagsArray.join(" ");
  69455. }
  69456. else {
  69457. return obj._tags;
  69458. }
  69459. };
  69460. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69461. // a tag cannot start with '||', '&&', and '!'
  69462. // it cannot contain whitespaces
  69463. Tags.AddTagsTo = function (obj, tagsString) {
  69464. if (!tagsString) {
  69465. return;
  69466. }
  69467. if (typeof tagsString !== "string") {
  69468. return;
  69469. }
  69470. var tags = tagsString.split(" ");
  69471. tags.forEach(function (tag, index, array) {
  69472. Tags._AddTagTo(obj, tag);
  69473. });
  69474. };
  69475. Tags._AddTagTo = function (obj, tag) {
  69476. tag = tag.trim();
  69477. if (tag === "" || tag === "true" || tag === "false") {
  69478. return;
  69479. }
  69480. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69481. return;
  69482. }
  69483. Tags.EnableFor(obj);
  69484. obj._tags[tag] = true;
  69485. };
  69486. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69487. if (!Tags.HasTags(obj)) {
  69488. return;
  69489. }
  69490. var tags = tagsString.split(" ");
  69491. for (var t in tags) {
  69492. Tags._RemoveTagFrom(obj, tags[t]);
  69493. }
  69494. };
  69495. Tags._RemoveTagFrom = function (obj, tag) {
  69496. delete obj._tags[tag];
  69497. };
  69498. Tags.MatchesQuery = function (obj, tagsQuery) {
  69499. if (tagsQuery === undefined) {
  69500. return true;
  69501. }
  69502. if (tagsQuery === "") {
  69503. return Tags.HasTags(obj);
  69504. }
  69505. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69506. };
  69507. return Tags;
  69508. }());
  69509. BABYLON.Tags = Tags;
  69510. })(BABYLON || (BABYLON = {}));
  69511. //# sourceMappingURL=babylon.tags.js.map
  69512. var BABYLON;
  69513. (function (BABYLON) {
  69514. /**
  69515. * Class used to evalaute queries containing `and` and `or` operators
  69516. */
  69517. var AndOrNotEvaluator = /** @class */ (function () {
  69518. function AndOrNotEvaluator() {
  69519. }
  69520. /**
  69521. * Evaluate a query
  69522. * @param query defines the query to evaluate
  69523. * @param evaluateCallback defines the callback used to filter result
  69524. * @returns true if the query matches
  69525. */
  69526. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69527. if (!query.match(/\([^\(\)]*\)/g)) {
  69528. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69529. }
  69530. else {
  69531. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69532. // remove parenthesis
  69533. r = r.slice(1, r.length - 1);
  69534. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69535. });
  69536. }
  69537. if (query === "true") {
  69538. return true;
  69539. }
  69540. if (query === "false") {
  69541. return false;
  69542. }
  69543. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69544. };
  69545. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69546. evaluateCallback = evaluateCallback || (function (r) {
  69547. return r === "true" ? true : false;
  69548. });
  69549. var result;
  69550. var or = parenthesisContent.split("||");
  69551. for (var i in or) {
  69552. if (or.hasOwnProperty(i)) {
  69553. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69554. var and = ori.split("&&");
  69555. if (and.length > 1) {
  69556. for (var j = 0; j < and.length; ++j) {
  69557. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69558. if (andj !== "true" && andj !== "false") {
  69559. if (andj[0] === "!") {
  69560. result = !evaluateCallback(andj.substring(1));
  69561. }
  69562. else {
  69563. result = evaluateCallback(andj);
  69564. }
  69565. }
  69566. else {
  69567. result = andj === "true" ? true : false;
  69568. }
  69569. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69570. ori = "false";
  69571. break;
  69572. }
  69573. }
  69574. }
  69575. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69576. result = true;
  69577. break;
  69578. }
  69579. // result equals false (or undefined)
  69580. if (ori !== "true" && ori !== "false") {
  69581. if (ori[0] === "!") {
  69582. result = !evaluateCallback(ori.substring(1));
  69583. }
  69584. else {
  69585. result = evaluateCallback(ori);
  69586. }
  69587. }
  69588. else {
  69589. result = ori === "true" ? true : false;
  69590. }
  69591. }
  69592. }
  69593. // the whole parenthesis scope is replaced by 'true' or 'false'
  69594. return result ? "true" : "false";
  69595. };
  69596. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69597. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69598. // remove whitespaces
  69599. r = r.replace(/[\s]/g, function () { return ""; });
  69600. return r.length % 2 ? "!" : "";
  69601. });
  69602. booleanString = booleanString.trim();
  69603. if (booleanString === "!true") {
  69604. booleanString = "false";
  69605. }
  69606. else if (booleanString === "!false") {
  69607. booleanString = "true";
  69608. }
  69609. return booleanString;
  69610. };
  69611. return AndOrNotEvaluator;
  69612. }());
  69613. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69614. })(BABYLON || (BABYLON = {}));
  69615. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69616. var BABYLON;
  69617. (function (BABYLON) {
  69618. /**
  69619. * Class used to enable access to IndexedDB
  69620. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69621. */
  69622. var Database = /** @class */ (function () {
  69623. /**
  69624. * Creates a new Database
  69625. * @param urlToScene defines the url to load the scene
  69626. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69627. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69628. */
  69629. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69630. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69631. var _this = this;
  69632. // Handling various flavors of prefixed version of IndexedDB
  69633. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69634. this.callbackManifestChecked = callbackManifestChecked;
  69635. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69636. this.db = null;
  69637. this._enableSceneOffline = false;
  69638. this._enableTexturesOffline = false;
  69639. this.manifestVersionFound = 0;
  69640. this.mustUpdateRessources = false;
  69641. this.hasReachedQuota = false;
  69642. if (!Database.IDBStorageEnabled) {
  69643. this.callbackManifestChecked(true);
  69644. }
  69645. else {
  69646. if (disableManifestCheck) {
  69647. this._enableSceneOffline = true;
  69648. this._enableTexturesOffline = true;
  69649. this.manifestVersionFound = 1;
  69650. BABYLON.Tools.SetImmediate(function () {
  69651. _this.callbackManifestChecked(true);
  69652. });
  69653. }
  69654. else {
  69655. this._checkManifestFile();
  69656. }
  69657. }
  69658. }
  69659. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69660. /**
  69661. * Gets a boolean indicating if scene must be saved in the database
  69662. */
  69663. get: function () {
  69664. return this._enableSceneOffline;
  69665. },
  69666. enumerable: true,
  69667. configurable: true
  69668. });
  69669. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69670. /**
  69671. * Gets a boolean indicating if textures must be saved in the database
  69672. */
  69673. get: function () {
  69674. return this._enableTexturesOffline;
  69675. },
  69676. enumerable: true,
  69677. configurable: true
  69678. });
  69679. Database.prototype._checkManifestFile = function () {
  69680. var _this = this;
  69681. var noManifestFile = function () {
  69682. _this._enableSceneOffline = false;
  69683. _this._enableTexturesOffline = false;
  69684. _this.callbackManifestChecked(false);
  69685. };
  69686. var timeStampUsed = false;
  69687. var manifestURL = this.currentSceneUrl + ".manifest";
  69688. var xhr = new XMLHttpRequest();
  69689. if (navigator.onLine) {
  69690. // Adding a timestamp to by-pass browsers' cache
  69691. timeStampUsed = true;
  69692. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69693. }
  69694. xhr.open("GET", manifestURL, true);
  69695. xhr.addEventListener("load", function () {
  69696. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69697. try {
  69698. var manifestFile = JSON.parse(xhr.response);
  69699. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69700. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69701. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69702. _this.manifestVersionFound = manifestFile.version;
  69703. }
  69704. if (_this.callbackManifestChecked) {
  69705. _this.callbackManifestChecked(true);
  69706. }
  69707. }
  69708. catch (ex) {
  69709. noManifestFile();
  69710. }
  69711. }
  69712. else {
  69713. noManifestFile();
  69714. }
  69715. }, false);
  69716. xhr.addEventListener("error", function (event) {
  69717. if (timeStampUsed) {
  69718. timeStampUsed = false;
  69719. // Let's retry without the timeStamp
  69720. // It could fail when coupled with HTML5 Offline API
  69721. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69722. xhr.open("GET", retryManifestURL, true);
  69723. xhr.send();
  69724. }
  69725. else {
  69726. noManifestFile();
  69727. }
  69728. }, false);
  69729. try {
  69730. xhr.send();
  69731. }
  69732. catch (ex) {
  69733. BABYLON.Tools.Error("Error on XHR send request.");
  69734. this.callbackManifestChecked(false);
  69735. }
  69736. };
  69737. /**
  69738. * Open the database and make it available
  69739. * @param successCallback defines the callback to call on success
  69740. * @param errorCallback defines the callback to call on error
  69741. */
  69742. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69743. var _this = this;
  69744. var handleError = function () {
  69745. _this.isSupported = false;
  69746. if (errorCallback)
  69747. errorCallback();
  69748. };
  69749. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69750. // Your browser doesn't support IndexedDB
  69751. this.isSupported = false;
  69752. if (errorCallback)
  69753. errorCallback();
  69754. }
  69755. else {
  69756. // If the DB hasn't been opened or created yet
  69757. if (!this.db) {
  69758. this.hasReachedQuota = false;
  69759. this.isSupported = true;
  69760. var request = this.idbFactory.open("babylonjs", 1);
  69761. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69762. request.onerror = function (event) {
  69763. handleError();
  69764. };
  69765. // executes when a version change transaction cannot complete due to other active transactions
  69766. request.onblocked = function (event) {
  69767. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69768. handleError();
  69769. };
  69770. // DB has been opened successfully
  69771. request.onsuccess = function (event) {
  69772. _this.db = request.result;
  69773. successCallback();
  69774. };
  69775. // Initialization of the DB. Creating Scenes & Textures stores
  69776. request.onupgradeneeded = function (event) {
  69777. _this.db = (event.target).result;
  69778. if (_this.db) {
  69779. try {
  69780. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69781. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69782. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69783. }
  69784. catch (ex) {
  69785. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69786. handleError();
  69787. }
  69788. }
  69789. };
  69790. }
  69791. // DB has already been created and opened
  69792. else {
  69793. if (successCallback)
  69794. successCallback();
  69795. }
  69796. }
  69797. };
  69798. /**
  69799. * Loads an image from the database
  69800. * @param url defines the url to load from
  69801. * @param image defines the target DOM image
  69802. */
  69803. Database.prototype.loadImageFromDB = function (url, image) {
  69804. var _this = this;
  69805. var completeURL = Database._ReturnFullUrlLocation(url);
  69806. var saveAndLoadImage = function () {
  69807. if (!_this.hasReachedQuota && _this.db !== null) {
  69808. // the texture is not yet in the DB, let's try to save it
  69809. _this._saveImageIntoDBAsync(completeURL, image);
  69810. }
  69811. // If the texture is not in the DB and we've reached the DB quota limit
  69812. // let's load it directly from the web
  69813. else {
  69814. image.src = url;
  69815. }
  69816. };
  69817. if (!this.mustUpdateRessources) {
  69818. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69819. }
  69820. // First time we're download the images or update requested in the manifest file by a version change
  69821. else {
  69822. saveAndLoadImage();
  69823. }
  69824. };
  69825. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69826. if (this.isSupported && this.db !== null) {
  69827. var texture;
  69828. var transaction = this.db.transaction(["textures"]);
  69829. transaction.onabort = function (event) {
  69830. image.src = url;
  69831. };
  69832. transaction.oncomplete = function (event) {
  69833. var blobTextureURL;
  69834. if (texture) {
  69835. var URL = window.URL || window.webkitURL;
  69836. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69837. image.onerror = function () {
  69838. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69839. image.src = url;
  69840. };
  69841. image.src = blobTextureURL;
  69842. }
  69843. else {
  69844. notInDBCallback();
  69845. }
  69846. };
  69847. var getRequest = transaction.objectStore("textures").get(url);
  69848. getRequest.onsuccess = function (event) {
  69849. texture = (event.target).result;
  69850. };
  69851. getRequest.onerror = function (event) {
  69852. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69853. image.src = url;
  69854. };
  69855. }
  69856. else {
  69857. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69858. image.src = url;
  69859. }
  69860. };
  69861. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69862. var _this = this;
  69863. if (this.isSupported) {
  69864. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69865. var generateBlobUrl = function () {
  69866. var blobTextureURL;
  69867. if (blob) {
  69868. var URL = window.URL || window.webkitURL;
  69869. try {
  69870. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69871. }
  69872. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69873. catch (ex) {
  69874. blobTextureURL = URL.createObjectURL(blob);
  69875. }
  69876. }
  69877. if (blobTextureURL) {
  69878. image.src = blobTextureURL;
  69879. }
  69880. };
  69881. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69882. var xhr = new XMLHttpRequest(), blob;
  69883. xhr.open("GET", url, true);
  69884. xhr.responseType = "blob";
  69885. xhr.addEventListener("load", function () {
  69886. if (xhr.status === 200 && _this.db) {
  69887. // Blob as response (XHR2)
  69888. blob = xhr.response;
  69889. var transaction = _this.db.transaction(["textures"], "readwrite");
  69890. // the transaction could abort because of a QuotaExceededError error
  69891. transaction.onabort = function (event) {
  69892. try {
  69893. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69894. var srcElement = (event.srcElement || event.target);
  69895. var error = srcElement.error;
  69896. if (error && error.name === "QuotaExceededError") {
  69897. _this.hasReachedQuota = true;
  69898. }
  69899. }
  69900. catch (ex) { }
  69901. generateBlobUrl();
  69902. };
  69903. transaction.oncomplete = function (event) {
  69904. generateBlobUrl();
  69905. };
  69906. var newTexture = { textureUrl: url, data: blob };
  69907. try {
  69908. // Put the blob into the dabase
  69909. var addRequest = transaction.objectStore("textures").put(newTexture);
  69910. addRequest.onsuccess = function (event) {
  69911. };
  69912. addRequest.onerror = function (event) {
  69913. generateBlobUrl();
  69914. };
  69915. }
  69916. catch (ex) {
  69917. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69918. if (ex.code === 25) {
  69919. Database.IsUASupportingBlobStorage = false;
  69920. }
  69921. image.src = url;
  69922. }
  69923. }
  69924. else {
  69925. image.src = url;
  69926. }
  69927. }, false);
  69928. xhr.addEventListener("error", function (event) {
  69929. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69930. image.src = url;
  69931. }, false);
  69932. xhr.send();
  69933. }
  69934. else {
  69935. image.src = url;
  69936. }
  69937. }
  69938. else {
  69939. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69940. image.src = url;
  69941. }
  69942. };
  69943. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69944. var _this = this;
  69945. var updateVersion = function () {
  69946. // the version is not yet in the DB or we need to update it
  69947. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69948. };
  69949. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69950. };
  69951. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69952. var _this = this;
  69953. if (this.isSupported && this.db) {
  69954. var version;
  69955. try {
  69956. var transaction = this.db.transaction(["versions"]);
  69957. transaction.oncomplete = function (event) {
  69958. if (version) {
  69959. // If the version in the JSON file is different from the version in DB
  69960. if (_this.manifestVersionFound !== version.data) {
  69961. _this.mustUpdateRessources = true;
  69962. updateInDBCallback();
  69963. }
  69964. else {
  69965. callback(version.data);
  69966. }
  69967. }
  69968. // version was not found in DB
  69969. else {
  69970. _this.mustUpdateRessources = true;
  69971. updateInDBCallback();
  69972. }
  69973. };
  69974. transaction.onabort = function (event) {
  69975. callback(-1);
  69976. };
  69977. var getRequest = transaction.objectStore("versions").get(url);
  69978. getRequest.onsuccess = function (event) {
  69979. version = (event.target).result;
  69980. };
  69981. getRequest.onerror = function (event) {
  69982. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69983. callback(-1);
  69984. };
  69985. }
  69986. catch (ex) {
  69987. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69988. callback(-1);
  69989. }
  69990. }
  69991. else {
  69992. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69993. callback(-1);
  69994. }
  69995. };
  69996. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69997. var _this = this;
  69998. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69999. try {
  70000. // Open a transaction to the database
  70001. var transaction = this.db.transaction(["versions"], "readwrite");
  70002. // the transaction could abort because of a QuotaExceededError error
  70003. transaction.onabort = function (event) {
  70004. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70005. var error = event.srcElement['error'];
  70006. if (error && error.name === "QuotaExceededError") {
  70007. _this.hasReachedQuota = true;
  70008. }
  70009. }
  70010. catch (ex) { }
  70011. callback(-1);
  70012. };
  70013. transaction.oncomplete = function (event) {
  70014. callback(_this.manifestVersionFound);
  70015. };
  70016. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70017. // Put the scene into the database
  70018. var addRequest = transaction.objectStore("versions").put(newVersion);
  70019. addRequest.onsuccess = function (event) {
  70020. };
  70021. addRequest.onerror = function (event) {
  70022. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70023. };
  70024. }
  70025. catch (ex) {
  70026. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70027. callback(-1);
  70028. }
  70029. }
  70030. else {
  70031. callback(-1);
  70032. }
  70033. };
  70034. /**
  70035. * Loads a file from database
  70036. * @param url defines the URL to load from
  70037. * @param sceneLoaded defines a callback to call on success
  70038. * @param progressCallBack defines a callback to call when progress changed
  70039. * @param errorCallback defines a callback to call on error
  70040. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70041. */
  70042. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70043. var _this = this;
  70044. var completeUrl = Database._ReturnFullUrlLocation(url);
  70045. var saveAndLoadFile = function () {
  70046. // the scene is not yet in the DB, let's try to save it
  70047. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  70048. };
  70049. this._checkVersionFromDB(completeUrl, function (version) {
  70050. if (version !== -1) {
  70051. if (!_this.mustUpdateRessources) {
  70052. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70053. }
  70054. else {
  70055. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  70056. }
  70057. }
  70058. else {
  70059. if (errorCallback) {
  70060. errorCallback();
  70061. }
  70062. }
  70063. });
  70064. };
  70065. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70066. if (this.isSupported && this.db) {
  70067. var targetStore;
  70068. if (url.indexOf(".babylon") !== -1) {
  70069. targetStore = "scenes";
  70070. }
  70071. else {
  70072. targetStore = "textures";
  70073. }
  70074. var file;
  70075. var transaction = this.db.transaction([targetStore]);
  70076. transaction.oncomplete = function (event) {
  70077. if (file) {
  70078. callback(file.data);
  70079. }
  70080. // file was not found in DB
  70081. else {
  70082. notInDBCallback();
  70083. }
  70084. };
  70085. transaction.onabort = function (event) {
  70086. notInDBCallback();
  70087. };
  70088. var getRequest = transaction.objectStore(targetStore).get(url);
  70089. getRequest.onsuccess = function (event) {
  70090. file = (event.target).result;
  70091. };
  70092. getRequest.onerror = function (event) {
  70093. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70094. notInDBCallback();
  70095. };
  70096. }
  70097. else {
  70098. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70099. callback();
  70100. }
  70101. };
  70102. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  70103. var _this = this;
  70104. if (this.isSupported) {
  70105. var targetStore;
  70106. if (url.indexOf(".babylon") !== -1) {
  70107. targetStore = "scenes";
  70108. }
  70109. else {
  70110. targetStore = "textures";
  70111. }
  70112. // Create XHR
  70113. var xhr = new XMLHttpRequest();
  70114. var fileData;
  70115. xhr.open("GET", url, true);
  70116. if (useArrayBuffer) {
  70117. xhr.responseType = "arraybuffer";
  70118. }
  70119. if (progressCallback) {
  70120. xhr.onprogress = progressCallback;
  70121. }
  70122. xhr.addEventListener("load", function () {
  70123. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  70124. // Blob as response (XHR2)
  70125. //fileData = xhr.responseText;
  70126. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70127. if (!_this.hasReachedQuota && _this.db) {
  70128. // Open a transaction to the database
  70129. var transaction = _this.db.transaction([targetStore], "readwrite");
  70130. // the transaction could abort because of a QuotaExceededError error
  70131. transaction.onabort = function (event) {
  70132. try {
  70133. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70134. var error = event.srcElement['error'];
  70135. if (error && error.name === "QuotaExceededError") {
  70136. _this.hasReachedQuota = true;
  70137. }
  70138. }
  70139. catch (ex) { }
  70140. callback(fileData);
  70141. };
  70142. transaction.oncomplete = function (event) {
  70143. callback(fileData);
  70144. };
  70145. var newFile;
  70146. if (targetStore === "scenes") {
  70147. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70148. }
  70149. else {
  70150. newFile = { textureUrl: url, data: fileData };
  70151. }
  70152. try {
  70153. // Put the scene into the database
  70154. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70155. addRequest.onsuccess = function (event) {
  70156. };
  70157. addRequest.onerror = function (event) {
  70158. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70159. };
  70160. }
  70161. catch (ex) {
  70162. callback(fileData);
  70163. }
  70164. }
  70165. else {
  70166. callback(fileData);
  70167. }
  70168. }
  70169. else {
  70170. callback();
  70171. }
  70172. }, false);
  70173. xhr.addEventListener("error", function (event) {
  70174. BABYLON.Tools.Error("error on XHR request.");
  70175. callback();
  70176. }, false);
  70177. xhr.send();
  70178. }
  70179. else {
  70180. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70181. callback();
  70182. }
  70183. };
  70184. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70185. Database.IsUASupportingBlobStorage = true;
  70186. /** Gets a boolean indicating if Database storate is enabled */
  70187. Database.IDBStorageEnabled = true;
  70188. Database._ParseURL = function (url) {
  70189. var a = document.createElement('a');
  70190. a.href = url;
  70191. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70192. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70193. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70194. return absLocation;
  70195. };
  70196. Database._ReturnFullUrlLocation = function (url) {
  70197. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70198. return (Database._ParseURL(window.location.href) + url);
  70199. }
  70200. else {
  70201. return url;
  70202. }
  70203. };
  70204. return Database;
  70205. }());
  70206. BABYLON.Database = Database;
  70207. })(BABYLON || (BABYLON = {}));
  70208. //# sourceMappingURL=babylon.database.js.map
  70209. var BABYLON;
  70210. (function (BABYLON) {
  70211. var FresnelParameters = /** @class */ (function () {
  70212. function FresnelParameters() {
  70213. this._isEnabled = true;
  70214. this.leftColor = BABYLON.Color3.White();
  70215. this.rightColor = BABYLON.Color3.Black();
  70216. this.bias = 0;
  70217. this.power = 1;
  70218. }
  70219. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70220. get: function () {
  70221. return this._isEnabled;
  70222. },
  70223. set: function (value) {
  70224. if (this._isEnabled === value) {
  70225. return;
  70226. }
  70227. this._isEnabled = value;
  70228. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. FresnelParameters.prototype.clone = function () {
  70234. var newFresnelParameters = new FresnelParameters();
  70235. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70236. return newFresnelParameters;
  70237. };
  70238. FresnelParameters.prototype.serialize = function () {
  70239. var serializationObject = {};
  70240. serializationObject.isEnabled = this.isEnabled;
  70241. serializationObject.leftColor = this.leftColor.asArray();
  70242. serializationObject.rightColor = this.rightColor.asArray();
  70243. serializationObject.bias = this.bias;
  70244. serializationObject.power = this.power;
  70245. return serializationObject;
  70246. };
  70247. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70248. var fresnelParameters = new FresnelParameters();
  70249. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70250. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70251. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70252. fresnelParameters.bias = parsedFresnelParameters.bias;
  70253. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70254. return fresnelParameters;
  70255. };
  70256. return FresnelParameters;
  70257. }());
  70258. BABYLON.FresnelParameters = FresnelParameters;
  70259. })(BABYLON || (BABYLON = {}));
  70260. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70261. var BABYLON;
  70262. (function (BABYLON) {
  70263. var MultiMaterial = /** @class */ (function (_super) {
  70264. __extends(MultiMaterial, _super);
  70265. function MultiMaterial(name, scene) {
  70266. var _this = _super.call(this, name, scene, true) || this;
  70267. scene.multiMaterials.push(_this);
  70268. _this.subMaterials = new Array();
  70269. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70270. return _this;
  70271. }
  70272. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70273. get: function () {
  70274. return this._subMaterials;
  70275. },
  70276. set: function (value) {
  70277. this._subMaterials = value;
  70278. this._hookArray(value);
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. MultiMaterial.prototype._hookArray = function (array) {
  70284. var _this = this;
  70285. var oldPush = array.push;
  70286. array.push = function () {
  70287. var items = [];
  70288. for (var _i = 0; _i < arguments.length; _i++) {
  70289. items[_i] = arguments[_i];
  70290. }
  70291. var result = oldPush.apply(array, items);
  70292. _this._markAllSubMeshesAsTexturesDirty();
  70293. return result;
  70294. };
  70295. var oldSplice = array.splice;
  70296. array.splice = function (index, deleteCount) {
  70297. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70298. _this._markAllSubMeshesAsTexturesDirty();
  70299. return deleted;
  70300. };
  70301. };
  70302. // Properties
  70303. MultiMaterial.prototype.getSubMaterial = function (index) {
  70304. if (index < 0 || index >= this.subMaterials.length) {
  70305. return this.getScene().defaultMaterial;
  70306. }
  70307. return this.subMaterials[index];
  70308. };
  70309. MultiMaterial.prototype.getActiveTextures = function () {
  70310. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70311. if (subMaterial) {
  70312. return subMaterial.getActiveTextures();
  70313. }
  70314. else {
  70315. return [];
  70316. }
  70317. }));
  70318. var _a;
  70319. };
  70320. // Methods
  70321. MultiMaterial.prototype.getClassName = function () {
  70322. return "MultiMaterial";
  70323. };
  70324. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70325. for (var index = 0; index < this.subMaterials.length; index++) {
  70326. var subMaterial = this.subMaterials[index];
  70327. if (subMaterial) {
  70328. if (subMaterial.storeEffectOnSubMeshes) {
  70329. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70330. return false;
  70331. }
  70332. continue;
  70333. }
  70334. if (!subMaterial.isReady(mesh)) {
  70335. return false;
  70336. }
  70337. }
  70338. }
  70339. return true;
  70340. };
  70341. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70342. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70343. for (var index = 0; index < this.subMaterials.length; index++) {
  70344. var subMaterial = null;
  70345. var current = this.subMaterials[index];
  70346. if (cloneChildren && current) {
  70347. subMaterial = current.clone(name + "-" + current.name);
  70348. }
  70349. else {
  70350. subMaterial = this.subMaterials[index];
  70351. }
  70352. newMultiMaterial.subMaterials.push(subMaterial);
  70353. }
  70354. return newMultiMaterial;
  70355. };
  70356. MultiMaterial.prototype.serialize = function () {
  70357. var serializationObject = {};
  70358. serializationObject.name = this.name;
  70359. serializationObject.id = this.id;
  70360. if (BABYLON.Tags) {
  70361. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70362. }
  70363. serializationObject.materials = [];
  70364. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70365. var subMat = this.subMaterials[matIndex];
  70366. if (subMat) {
  70367. serializationObject.materials.push(subMat.id);
  70368. }
  70369. else {
  70370. serializationObject.materials.push(null);
  70371. }
  70372. }
  70373. return serializationObject;
  70374. };
  70375. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70376. var scene = this.getScene();
  70377. if (!scene) {
  70378. return;
  70379. }
  70380. var index = scene.multiMaterials.indexOf(this);
  70381. if (index >= 0) {
  70382. scene.multiMaterials.splice(index, 1);
  70383. }
  70384. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70385. };
  70386. return MultiMaterial;
  70387. }(BABYLON.Material));
  70388. BABYLON.MultiMaterial = MultiMaterial;
  70389. })(BABYLON || (BABYLON = {}));
  70390. //# sourceMappingURL=babylon.multiMaterial.js.map
  70391. var BABYLON;
  70392. (function (BABYLON) {
  70393. var FreeCameraTouchInput = /** @class */ (function () {
  70394. function FreeCameraTouchInput() {
  70395. this._offsetX = null;
  70396. this._offsetY = null;
  70397. this._pointerPressed = new Array();
  70398. this.touchAngularSensibility = 200000.0;
  70399. this.touchMoveSensibility = 250.0;
  70400. }
  70401. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70402. var _this = this;
  70403. var previousPosition = null;
  70404. if (this._pointerInput === undefined) {
  70405. this._onLostFocus = function (evt) {
  70406. _this._offsetX = null;
  70407. _this._offsetY = null;
  70408. };
  70409. this._pointerInput = function (p, s) {
  70410. var evt = p.event;
  70411. if (evt.pointerType === "mouse") {
  70412. return;
  70413. }
  70414. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70415. if (!noPreventDefault) {
  70416. evt.preventDefault();
  70417. }
  70418. _this._pointerPressed.push(evt.pointerId);
  70419. if (_this._pointerPressed.length !== 1) {
  70420. return;
  70421. }
  70422. previousPosition = {
  70423. x: evt.clientX,
  70424. y: evt.clientY
  70425. };
  70426. }
  70427. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70428. if (!noPreventDefault) {
  70429. evt.preventDefault();
  70430. }
  70431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70432. if (index === -1) {
  70433. return;
  70434. }
  70435. _this._pointerPressed.splice(index, 1);
  70436. if (index != 0) {
  70437. return;
  70438. }
  70439. previousPosition = null;
  70440. _this._offsetX = null;
  70441. _this._offsetY = null;
  70442. }
  70443. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70444. if (!noPreventDefault) {
  70445. evt.preventDefault();
  70446. }
  70447. if (!previousPosition) {
  70448. return;
  70449. }
  70450. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70451. if (index != 0) {
  70452. return;
  70453. }
  70454. _this._offsetX = evt.clientX - previousPosition.x;
  70455. _this._offsetY = -(evt.clientY - previousPosition.y);
  70456. }
  70457. };
  70458. }
  70459. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70460. if (this._onLostFocus) {
  70461. element.addEventListener("blur", this._onLostFocus);
  70462. }
  70463. };
  70464. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70465. if (this._pointerInput && element) {
  70466. if (this._observer) {
  70467. this.camera.getScene().onPointerObservable.remove(this._observer);
  70468. this._observer = null;
  70469. }
  70470. if (this._onLostFocus) {
  70471. element.removeEventListener("blur", this._onLostFocus);
  70472. this._onLostFocus = null;
  70473. }
  70474. this._pointerPressed = [];
  70475. this._offsetX = null;
  70476. this._offsetY = null;
  70477. }
  70478. };
  70479. FreeCameraTouchInput.prototype.checkInputs = function () {
  70480. if (this._offsetX && this._offsetY) {
  70481. var camera = this.camera;
  70482. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70483. if (this._pointerPressed.length > 1) {
  70484. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70485. }
  70486. else {
  70487. var speed = camera._computeLocalCameraSpeed();
  70488. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70489. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70490. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70491. }
  70492. }
  70493. };
  70494. FreeCameraTouchInput.prototype.getClassName = function () {
  70495. return "FreeCameraTouchInput";
  70496. };
  70497. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70498. return "touch";
  70499. };
  70500. __decorate([
  70501. BABYLON.serialize()
  70502. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70503. __decorate([
  70504. BABYLON.serialize()
  70505. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70506. return FreeCameraTouchInput;
  70507. }());
  70508. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70509. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70510. })(BABYLON || (BABYLON = {}));
  70511. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70512. var BABYLON;
  70513. (function (BABYLON) {
  70514. // We're mainly based on the logic defined into the FreeCamera code
  70515. var TouchCamera = /** @class */ (function (_super) {
  70516. __extends(TouchCamera, _super);
  70517. //-- end properties for backward compatibility for inputs
  70518. function TouchCamera(name, position, scene) {
  70519. var _this = _super.call(this, name, position, scene) || this;
  70520. _this.inputs.addTouch();
  70521. _this._setupInputs();
  70522. return _this;
  70523. }
  70524. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70525. //-- Begin properties for backward compatibility for inputs
  70526. get: function () {
  70527. var touch = this.inputs.attached["touch"];
  70528. if (touch)
  70529. return touch.touchAngularSensibility;
  70530. return 0;
  70531. },
  70532. set: function (value) {
  70533. var touch = this.inputs.attached["touch"];
  70534. if (touch)
  70535. touch.touchAngularSensibility = value;
  70536. },
  70537. enumerable: true,
  70538. configurable: true
  70539. });
  70540. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70541. get: function () {
  70542. var touch = this.inputs.attached["touch"];
  70543. if (touch)
  70544. return touch.touchMoveSensibility;
  70545. return 0;
  70546. },
  70547. set: function (value) {
  70548. var touch = this.inputs.attached["touch"];
  70549. if (touch)
  70550. touch.touchMoveSensibility = value;
  70551. },
  70552. enumerable: true,
  70553. configurable: true
  70554. });
  70555. TouchCamera.prototype.getClassName = function () {
  70556. return "TouchCamera";
  70557. };
  70558. TouchCamera.prototype._setupInputs = function () {
  70559. var mouse = this.inputs.attached["mouse"];
  70560. if (mouse) {
  70561. mouse.touchEnabled = false;
  70562. }
  70563. };
  70564. return TouchCamera;
  70565. }(BABYLON.FreeCamera));
  70566. BABYLON.TouchCamera = TouchCamera;
  70567. })(BABYLON || (BABYLON = {}));
  70568. //# sourceMappingURL=babylon.touchCamera.js.map
  70569. var BABYLON;
  70570. (function (BABYLON) {
  70571. var ProceduralTexture = /** @class */ (function (_super) {
  70572. __extends(ProceduralTexture, _super);
  70573. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70574. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70575. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70576. if (isCube === void 0) { isCube = false; }
  70577. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70578. _this.isCube = isCube;
  70579. _this.isEnabled = true;
  70580. _this._currentRefreshId = -1;
  70581. _this._refreshRate = 1;
  70582. _this._vertexBuffers = {};
  70583. _this._uniforms = new Array();
  70584. _this._samplers = new Array();
  70585. _this._textures = {};
  70586. _this._floats = {};
  70587. _this._floatsArrays = {};
  70588. _this._colors3 = {};
  70589. _this._colors4 = {};
  70590. _this._vectors2 = {};
  70591. _this._vectors3 = {};
  70592. _this._matrices = {};
  70593. _this._fallbackTextureUsed = false;
  70594. scene.proceduralTextures.push(_this);
  70595. _this._engine = scene.getEngine();
  70596. _this.name = name;
  70597. _this.isRenderTarget = true;
  70598. _this._size = size;
  70599. _this._generateMipMaps = generateMipMaps;
  70600. _this.setFragment(fragment);
  70601. _this._fallbackTexture = fallbackTexture;
  70602. if (isCube) {
  70603. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70604. _this.setFloat("face", 0);
  70605. }
  70606. else {
  70607. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70608. }
  70609. // VBO
  70610. var vertices = [];
  70611. vertices.push(1, 1);
  70612. vertices.push(-1, 1);
  70613. vertices.push(-1, -1);
  70614. vertices.push(1, -1);
  70615. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70616. _this._createIndexBuffer();
  70617. return _this;
  70618. }
  70619. ProceduralTexture.prototype._createIndexBuffer = function () {
  70620. var engine = this._engine;
  70621. // Indices
  70622. var indices = [];
  70623. indices.push(0);
  70624. indices.push(1);
  70625. indices.push(2);
  70626. indices.push(0);
  70627. indices.push(2);
  70628. indices.push(3);
  70629. this._indexBuffer = engine.createIndexBuffer(indices);
  70630. };
  70631. ProceduralTexture.prototype._rebuild = function () {
  70632. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70633. if (vb) {
  70634. vb._rebuild();
  70635. }
  70636. this._createIndexBuffer();
  70637. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70638. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70639. }
  70640. };
  70641. ProceduralTexture.prototype.reset = function () {
  70642. if (this._effect === undefined) {
  70643. return;
  70644. }
  70645. var engine = this._engine;
  70646. engine._releaseEffect(this._effect);
  70647. };
  70648. ProceduralTexture.prototype.isReady = function () {
  70649. var _this = this;
  70650. var engine = this._engine;
  70651. var shaders;
  70652. if (!this._fragment) {
  70653. return false;
  70654. }
  70655. if (this._fallbackTextureUsed) {
  70656. return true;
  70657. }
  70658. if (this._fragment.fragmentElement !== undefined) {
  70659. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70660. }
  70661. else {
  70662. shaders = { vertex: "procedural", fragment: this._fragment };
  70663. }
  70664. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70665. _this.releaseInternalTexture();
  70666. if (_this._fallbackTexture) {
  70667. _this._texture = _this._fallbackTexture._texture;
  70668. if (_this._texture) {
  70669. _this._texture.incrementReferences();
  70670. }
  70671. }
  70672. _this._fallbackTextureUsed = true;
  70673. });
  70674. return this._effect.isReady();
  70675. };
  70676. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70677. this._currentRefreshId = -1;
  70678. };
  70679. ProceduralTexture.prototype.setFragment = function (fragment) {
  70680. this._fragment = fragment;
  70681. };
  70682. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70683. get: function () {
  70684. return this._refreshRate;
  70685. },
  70686. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70687. set: function (value) {
  70688. this._refreshRate = value;
  70689. this.resetRefreshCounter();
  70690. },
  70691. enumerable: true,
  70692. configurable: true
  70693. });
  70694. ProceduralTexture.prototype._shouldRender = function () {
  70695. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70696. return false;
  70697. }
  70698. if (this._fallbackTextureUsed) {
  70699. return false;
  70700. }
  70701. if (this._currentRefreshId === -1) { // At least render once
  70702. this._currentRefreshId = 1;
  70703. return true;
  70704. }
  70705. if (this.refreshRate === this._currentRefreshId) {
  70706. this._currentRefreshId = 1;
  70707. return true;
  70708. }
  70709. this._currentRefreshId++;
  70710. return false;
  70711. };
  70712. ProceduralTexture.prototype.getRenderSize = function () {
  70713. return this._size;
  70714. };
  70715. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70716. if (this._fallbackTextureUsed) {
  70717. return;
  70718. }
  70719. this.releaseInternalTexture();
  70720. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70721. // Update properties
  70722. this._size = size;
  70723. this._generateMipMaps = generateMipMaps;
  70724. };
  70725. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70726. if (this._uniforms.indexOf(uniformName) === -1) {
  70727. this._uniforms.push(uniformName);
  70728. }
  70729. };
  70730. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70731. if (this._samplers.indexOf(name) === -1) {
  70732. this._samplers.push(name);
  70733. }
  70734. this._textures[name] = texture;
  70735. return this;
  70736. };
  70737. ProceduralTexture.prototype.setFloat = function (name, value) {
  70738. this._checkUniform(name);
  70739. this._floats[name] = value;
  70740. return this;
  70741. };
  70742. ProceduralTexture.prototype.setFloats = function (name, value) {
  70743. this._checkUniform(name);
  70744. this._floatsArrays[name] = value;
  70745. return this;
  70746. };
  70747. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70748. this._checkUniform(name);
  70749. this._colors3[name] = value;
  70750. return this;
  70751. };
  70752. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70753. this._checkUniform(name);
  70754. this._colors4[name] = value;
  70755. return this;
  70756. };
  70757. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70758. this._checkUniform(name);
  70759. this._vectors2[name] = value;
  70760. return this;
  70761. };
  70762. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70763. this._checkUniform(name);
  70764. this._vectors3[name] = value;
  70765. return this;
  70766. };
  70767. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70768. this._checkUniform(name);
  70769. this._matrices[name] = value;
  70770. return this;
  70771. };
  70772. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70773. var scene = this.getScene();
  70774. if (!scene) {
  70775. return;
  70776. }
  70777. var engine = this._engine;
  70778. // Render
  70779. engine.enableEffect(this._effect);
  70780. engine.setState(false);
  70781. // Texture
  70782. for (var name in this._textures) {
  70783. this._effect.setTexture(name, this._textures[name]);
  70784. }
  70785. // Float
  70786. for (name in this._floats) {
  70787. this._effect.setFloat(name, this._floats[name]);
  70788. }
  70789. // Floats
  70790. for (name in this._floatsArrays) {
  70791. this._effect.setArray(name, this._floatsArrays[name]);
  70792. }
  70793. // Color3
  70794. for (name in this._colors3) {
  70795. this._effect.setColor3(name, this._colors3[name]);
  70796. }
  70797. // Color4
  70798. for (name in this._colors4) {
  70799. var color = this._colors4[name];
  70800. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70801. }
  70802. // Vector2
  70803. for (name in this._vectors2) {
  70804. this._effect.setVector2(name, this._vectors2[name]);
  70805. }
  70806. // Vector3
  70807. for (name in this._vectors3) {
  70808. this._effect.setVector3(name, this._vectors3[name]);
  70809. }
  70810. // Matrix
  70811. for (name in this._matrices) {
  70812. this._effect.setMatrix(name, this._matrices[name]);
  70813. }
  70814. if (!this._texture) {
  70815. return;
  70816. }
  70817. if (this.isCube) {
  70818. for (var face = 0; face < 6; face++) {
  70819. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70820. // VBOs
  70821. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70822. this._effect.setFloat("face", face);
  70823. // Clear
  70824. engine.clear(scene.clearColor, true, true, true);
  70825. // Draw order
  70826. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70827. // Mipmaps
  70828. if (face === 5) {
  70829. engine.generateMipMapsForCubemap(this._texture);
  70830. }
  70831. }
  70832. }
  70833. else {
  70834. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70835. // VBOs
  70836. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70837. // Clear
  70838. engine.clear(scene.clearColor, true, true, true);
  70839. // Draw order
  70840. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70841. }
  70842. // Unbind
  70843. engine.unBindFramebuffer(this._texture, this.isCube);
  70844. if (this.onGenerated) {
  70845. this.onGenerated();
  70846. }
  70847. };
  70848. ProceduralTexture.prototype.clone = function () {
  70849. var textureSize = this.getSize();
  70850. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70851. // Base texture
  70852. newTexture.hasAlpha = this.hasAlpha;
  70853. newTexture.level = this.level;
  70854. // RenderTarget Texture
  70855. newTexture.coordinatesMode = this.coordinatesMode;
  70856. return newTexture;
  70857. };
  70858. ProceduralTexture.prototype.dispose = function () {
  70859. var scene = this.getScene();
  70860. if (!scene) {
  70861. return;
  70862. }
  70863. var index = scene.proceduralTextures.indexOf(this);
  70864. if (index >= 0) {
  70865. scene.proceduralTextures.splice(index, 1);
  70866. }
  70867. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70868. if (vertexBuffer) {
  70869. vertexBuffer.dispose();
  70870. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70871. }
  70872. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70873. this._indexBuffer = null;
  70874. }
  70875. _super.prototype.dispose.call(this);
  70876. };
  70877. __decorate([
  70878. BABYLON.serialize()
  70879. ], ProceduralTexture.prototype, "_size", void 0);
  70880. __decorate([
  70881. BABYLON.serialize()
  70882. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70883. __decorate([
  70884. BABYLON.serialize()
  70885. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70886. __decorate([
  70887. BABYLON.serialize()
  70888. ], ProceduralTexture.prototype, "refreshRate", null);
  70889. return ProceduralTexture;
  70890. }(BABYLON.Texture));
  70891. BABYLON.ProceduralTexture = ProceduralTexture;
  70892. })(BABYLON || (BABYLON = {}));
  70893. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70894. var BABYLON;
  70895. (function (BABYLON) {
  70896. var CustomProceduralTexture = /** @class */ (function (_super) {
  70897. __extends(CustomProceduralTexture, _super);
  70898. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70899. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70900. _this._animate = true;
  70901. _this._time = 0;
  70902. _this._texturePath = texturePath;
  70903. //Try to load json
  70904. _this.loadJson(texturePath);
  70905. _this.refreshRate = 1;
  70906. return _this;
  70907. }
  70908. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70909. var _this = this;
  70910. var noConfigFile = function () {
  70911. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70912. try {
  70913. _this.setFragment(_this._texturePath);
  70914. }
  70915. catch (ex) {
  70916. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70917. }
  70918. };
  70919. var configFileUrl = jsonUrl + "/config.json";
  70920. var xhr = new XMLHttpRequest();
  70921. xhr.open("GET", configFileUrl, true);
  70922. xhr.addEventListener("load", function () {
  70923. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70924. try {
  70925. _this._config = JSON.parse(xhr.response);
  70926. _this.updateShaderUniforms();
  70927. _this.updateTextures();
  70928. _this.setFragment(_this._texturePath + "/custom");
  70929. _this._animate = _this._config.animate;
  70930. _this.refreshRate = _this._config.refreshrate;
  70931. }
  70932. catch (ex) {
  70933. noConfigFile();
  70934. }
  70935. }
  70936. else {
  70937. noConfigFile();
  70938. }
  70939. }, false);
  70940. xhr.addEventListener("error", function () {
  70941. noConfigFile();
  70942. }, false);
  70943. try {
  70944. xhr.send();
  70945. }
  70946. catch (ex) {
  70947. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70948. }
  70949. };
  70950. CustomProceduralTexture.prototype.isReady = function () {
  70951. if (!_super.prototype.isReady.call(this)) {
  70952. return false;
  70953. }
  70954. for (var name in this._textures) {
  70955. var texture = this._textures[name];
  70956. if (!texture.isReady()) {
  70957. return false;
  70958. }
  70959. }
  70960. return true;
  70961. };
  70962. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70963. var scene = this.getScene();
  70964. if (this._animate && scene) {
  70965. this._time += scene.getAnimationRatio() * 0.03;
  70966. this.updateShaderUniforms();
  70967. }
  70968. _super.prototype.render.call(this, useCameraPostProcess);
  70969. };
  70970. CustomProceduralTexture.prototype.updateTextures = function () {
  70971. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70972. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70973. }
  70974. };
  70975. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70976. if (this._config) {
  70977. for (var j = 0; j < this._config.uniforms.length; j++) {
  70978. var uniform = this._config.uniforms[j];
  70979. switch (uniform.type) {
  70980. case "float":
  70981. this.setFloat(uniform.name, uniform.value);
  70982. break;
  70983. case "color3":
  70984. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70985. break;
  70986. case "color4":
  70987. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70988. break;
  70989. case "vector2":
  70990. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70991. break;
  70992. case "vector3":
  70993. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70994. break;
  70995. }
  70996. }
  70997. }
  70998. this.setFloat("time", this._time);
  70999. };
  71000. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71001. get: function () {
  71002. return this._animate;
  71003. },
  71004. set: function (value) {
  71005. this._animate = value;
  71006. },
  71007. enumerable: true,
  71008. configurable: true
  71009. });
  71010. return CustomProceduralTexture;
  71011. }(BABYLON.ProceduralTexture));
  71012. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71013. })(BABYLON || (BABYLON = {}));
  71014. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71015. var BABYLON;
  71016. (function (BABYLON) {
  71017. var FreeCameraGamepadInput = /** @class */ (function () {
  71018. function FreeCameraGamepadInput() {
  71019. this.gamepadAngularSensibility = 200;
  71020. this.gamepadMoveSensibility = 40;
  71021. // private members
  71022. this._cameraTransform = BABYLON.Matrix.Identity();
  71023. this._deltaTransform = BABYLON.Vector3.Zero();
  71024. this._vector3 = BABYLON.Vector3.Zero();
  71025. this._vector2 = BABYLON.Vector2.Zero();
  71026. }
  71027. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71028. var _this = this;
  71029. var manager = this.camera.getScene().gamepadManager;
  71030. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71031. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71032. // prioritize XBOX gamepads.
  71033. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71034. _this.gamepad = gamepad;
  71035. }
  71036. }
  71037. });
  71038. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71039. if (_this.gamepad === gamepad) {
  71040. _this.gamepad = null;
  71041. }
  71042. });
  71043. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71044. };
  71045. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71046. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71047. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71048. this.gamepad = null;
  71049. };
  71050. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71051. if (this.gamepad && this.gamepad.leftStick) {
  71052. var camera = this.camera;
  71053. var LSValues = this.gamepad.leftStick;
  71054. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71055. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71056. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71057. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71058. var RSValues = this.gamepad.rightStick;
  71059. if (RSValues) {
  71060. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71061. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71062. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71063. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71064. }
  71065. else {
  71066. RSValues = { x: 0, y: 0 };
  71067. }
  71068. if (!camera.rotationQuaternion) {
  71069. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71070. }
  71071. else {
  71072. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71073. }
  71074. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71075. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71076. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71077. camera.cameraDirection.addInPlace(this._deltaTransform);
  71078. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71079. camera.cameraRotation.addInPlace(this._vector2);
  71080. }
  71081. };
  71082. FreeCameraGamepadInput.prototype.getClassName = function () {
  71083. return "FreeCameraGamepadInput";
  71084. };
  71085. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71086. return "gamepad";
  71087. };
  71088. __decorate([
  71089. BABYLON.serialize()
  71090. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71091. __decorate([
  71092. BABYLON.serialize()
  71093. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71094. return FreeCameraGamepadInput;
  71095. }());
  71096. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71097. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71098. })(BABYLON || (BABYLON = {}));
  71099. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71100. var BABYLON;
  71101. (function (BABYLON) {
  71102. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71103. function ArcRotateCameraGamepadInput() {
  71104. this.gamepadRotationSensibility = 80;
  71105. this.gamepadMoveSensibility = 40;
  71106. }
  71107. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71108. var _this = this;
  71109. var manager = this.camera.getScene().gamepadManager;
  71110. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71111. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71112. // prioritize XBOX gamepads.
  71113. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71114. _this.gamepad = gamepad;
  71115. }
  71116. }
  71117. });
  71118. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71119. if (_this.gamepad === gamepad) {
  71120. _this.gamepad = null;
  71121. }
  71122. });
  71123. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71124. };
  71125. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71126. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71127. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71128. this.gamepad = null;
  71129. };
  71130. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71131. if (this.gamepad) {
  71132. var camera = this.camera;
  71133. var RSValues = this.gamepad.rightStick;
  71134. if (RSValues) {
  71135. if (RSValues.x != 0) {
  71136. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71137. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71138. camera.inertialAlphaOffset += normalizedRX;
  71139. }
  71140. }
  71141. if (RSValues.y != 0) {
  71142. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71143. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71144. camera.inertialBetaOffset += normalizedRY;
  71145. }
  71146. }
  71147. }
  71148. var LSValues = this.gamepad.leftStick;
  71149. if (LSValues && LSValues.y != 0) {
  71150. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71151. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71152. this.camera.inertialRadiusOffset -= normalizedLY;
  71153. }
  71154. }
  71155. }
  71156. };
  71157. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71158. return "ArcRotateCameraGamepadInput";
  71159. };
  71160. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71161. return "gamepad";
  71162. };
  71163. __decorate([
  71164. BABYLON.serialize()
  71165. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71166. __decorate([
  71167. BABYLON.serialize()
  71168. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71169. return ArcRotateCameraGamepadInput;
  71170. }());
  71171. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71172. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71173. })(BABYLON || (BABYLON = {}));
  71174. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71175. var BABYLON;
  71176. (function (BABYLON) {
  71177. var GamepadManager = /** @class */ (function () {
  71178. function GamepadManager(_scene) {
  71179. var _this = this;
  71180. this._scene = _scene;
  71181. this._babylonGamepads = [];
  71182. this._oneGamepadConnected = false;
  71183. this._isMonitoring = false;
  71184. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71185. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71186. this._gamepadEventSupported = false;
  71187. }
  71188. else {
  71189. this._gamepadEventSupported = 'GamepadEvent' in window;
  71190. this._gamepadSupport = (navigator.getGamepads ||
  71191. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71192. }
  71193. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71194. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71195. for (var i in _this._babylonGamepads) {
  71196. var gamepad = _this._babylonGamepads[i];
  71197. if (gamepad && gamepad._isConnected) {
  71198. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71199. }
  71200. }
  71201. });
  71202. this._onGamepadConnectedEvent = function (evt) {
  71203. var gamepad = evt.gamepad;
  71204. if (gamepad.index in _this._babylonGamepads) {
  71205. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71206. return;
  71207. }
  71208. }
  71209. var newGamepad;
  71210. if (_this._babylonGamepads[gamepad.index]) {
  71211. newGamepad = _this._babylonGamepads[gamepad.index];
  71212. newGamepad.browserGamepad = gamepad;
  71213. newGamepad._isConnected = true;
  71214. }
  71215. else {
  71216. newGamepad = _this._addNewGamepad(gamepad);
  71217. }
  71218. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71219. _this._startMonitoringGamepads();
  71220. };
  71221. this._onGamepadDisconnectedEvent = function (evt) {
  71222. var gamepad = evt.gamepad;
  71223. // Remove the gamepad from the list of gamepads to monitor.
  71224. for (var i in _this._babylonGamepads) {
  71225. if (_this._babylonGamepads[i].index === gamepad.index) {
  71226. var disconnectedGamepad = _this._babylonGamepads[i];
  71227. disconnectedGamepad._isConnected = false;
  71228. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71229. break;
  71230. }
  71231. }
  71232. };
  71233. if (this._gamepadSupport) {
  71234. //first add already-connected gamepads
  71235. this._updateGamepadObjects();
  71236. if (this._babylonGamepads.length) {
  71237. this._startMonitoringGamepads();
  71238. }
  71239. // Checking if the gamepad connected event is supported (like in Firefox)
  71240. if (this._gamepadEventSupported) {
  71241. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71242. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71243. }
  71244. else {
  71245. this._startMonitoringGamepads();
  71246. }
  71247. }
  71248. }
  71249. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71250. get: function () {
  71251. return this._babylonGamepads;
  71252. },
  71253. enumerable: true,
  71254. configurable: true
  71255. });
  71256. GamepadManager.prototype.getGamepadByType = function (type) {
  71257. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71258. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71259. var gamepad = _a[_i];
  71260. if (gamepad && gamepad.type === type) {
  71261. return gamepad;
  71262. }
  71263. }
  71264. return null;
  71265. };
  71266. GamepadManager.prototype.dispose = function () {
  71267. if (this._gamepadEventSupported) {
  71268. if (this._onGamepadConnectedEvent) {
  71269. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71270. }
  71271. if (this._onGamepadDisconnectedEvent) {
  71272. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71273. }
  71274. this._onGamepadConnectedEvent = null;
  71275. this._onGamepadDisconnectedEvent = null;
  71276. }
  71277. this._babylonGamepads.forEach(function (gamepad) {
  71278. gamepad.dispose();
  71279. });
  71280. this.onGamepadConnectedObservable.clear();
  71281. this.onGamepadDisconnectedObservable.clear();
  71282. this._oneGamepadConnected = false;
  71283. this._stopMonitoringGamepads();
  71284. this._babylonGamepads = [];
  71285. };
  71286. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71287. if (!this._oneGamepadConnected) {
  71288. this._oneGamepadConnected = true;
  71289. }
  71290. var newGamepad;
  71291. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71292. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71293. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71294. }
  71295. // if pose is supported, use the (WebVR) pose enabled controller
  71296. else if (gamepad.pose) {
  71297. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71298. }
  71299. else {
  71300. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71301. }
  71302. this._babylonGamepads[newGamepad.index] = newGamepad;
  71303. return newGamepad;
  71304. };
  71305. GamepadManager.prototype._startMonitoringGamepads = function () {
  71306. if (!this._isMonitoring) {
  71307. this._isMonitoring = true;
  71308. //back-comp
  71309. if (!this._scene) {
  71310. this._checkGamepadsStatus();
  71311. }
  71312. }
  71313. };
  71314. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71315. this._isMonitoring = false;
  71316. };
  71317. GamepadManager.prototype._checkGamepadsStatus = function () {
  71318. var _this = this;
  71319. // Hack to be compatible Chrome
  71320. this._updateGamepadObjects();
  71321. for (var i in this._babylonGamepads) {
  71322. var gamepad = this._babylonGamepads[i];
  71323. if (!gamepad || !gamepad.isConnected) {
  71324. continue;
  71325. }
  71326. gamepad.update();
  71327. }
  71328. if (this._isMonitoring && !this._scene) {
  71329. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71330. }
  71331. };
  71332. // This function is called only on Chrome, which does not properly support
  71333. // connection/disconnection events and forces you to recopy again the gamepad object
  71334. GamepadManager.prototype._updateGamepadObjects = function () {
  71335. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71336. for (var i = 0; i < gamepads.length; i++) {
  71337. var gamepad = gamepads[i];
  71338. if (gamepad) {
  71339. if (!this._babylonGamepads[gamepad.index]) {
  71340. var newGamepad = this._addNewGamepad(gamepad);
  71341. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71342. }
  71343. else {
  71344. // Forced to copy again this object for Chrome for unknown reason
  71345. this._babylonGamepads[i].browserGamepad = gamepad;
  71346. if (!this._babylonGamepads[i].isConnected) {
  71347. this._babylonGamepads[i]._isConnected = true;
  71348. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71349. }
  71350. }
  71351. }
  71352. }
  71353. };
  71354. return GamepadManager;
  71355. }());
  71356. BABYLON.GamepadManager = GamepadManager;
  71357. })(BABYLON || (BABYLON = {}));
  71358. //# sourceMappingURL=babylon.gamepadManager.js.map
  71359. var BABYLON;
  71360. (function (BABYLON) {
  71361. var StickValues = /** @class */ (function () {
  71362. function StickValues(x, y) {
  71363. this.x = x;
  71364. this.y = y;
  71365. }
  71366. return StickValues;
  71367. }());
  71368. BABYLON.StickValues = StickValues;
  71369. var Gamepad = /** @class */ (function () {
  71370. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71371. if (leftStickX === void 0) { leftStickX = 0; }
  71372. if (leftStickY === void 0) { leftStickY = 1; }
  71373. if (rightStickX === void 0) { rightStickX = 2; }
  71374. if (rightStickY === void 0) { rightStickY = 3; }
  71375. this.id = id;
  71376. this.index = index;
  71377. this.browserGamepad = browserGamepad;
  71378. this._isConnected = true;
  71379. this._invertLeftStickY = false;
  71380. this.type = Gamepad.GAMEPAD;
  71381. this._leftStickAxisX = leftStickX;
  71382. this._leftStickAxisY = leftStickY;
  71383. this._rightStickAxisX = rightStickX;
  71384. this._rightStickAxisY = rightStickY;
  71385. if (this.browserGamepad.axes.length >= 2) {
  71386. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71387. }
  71388. if (this.browserGamepad.axes.length >= 4) {
  71389. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71390. }
  71391. }
  71392. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71393. get: function () {
  71394. return this._isConnected;
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. Gamepad.prototype.onleftstickchanged = function (callback) {
  71400. this._onleftstickchanged = callback;
  71401. };
  71402. Gamepad.prototype.onrightstickchanged = function (callback) {
  71403. this._onrightstickchanged = callback;
  71404. };
  71405. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71406. get: function () {
  71407. return this._leftStick;
  71408. },
  71409. set: function (newValues) {
  71410. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71411. this._onleftstickchanged(newValues);
  71412. }
  71413. this._leftStick = newValues;
  71414. },
  71415. enumerable: true,
  71416. configurable: true
  71417. });
  71418. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71419. get: function () {
  71420. return this._rightStick;
  71421. },
  71422. set: function (newValues) {
  71423. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71424. this._onrightstickchanged(newValues);
  71425. }
  71426. this._rightStick = newValues;
  71427. },
  71428. enumerable: true,
  71429. configurable: true
  71430. });
  71431. Gamepad.prototype.update = function () {
  71432. if (this._leftStick) {
  71433. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71434. if (this._invertLeftStickY) {
  71435. this.leftStick.y *= -1;
  71436. }
  71437. }
  71438. if (this._rightStick) {
  71439. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71440. }
  71441. };
  71442. Gamepad.prototype.dispose = function () {
  71443. };
  71444. Gamepad.GAMEPAD = 0;
  71445. Gamepad.GENERIC = 1;
  71446. Gamepad.XBOX = 2;
  71447. Gamepad.POSE_ENABLED = 3;
  71448. return Gamepad;
  71449. }());
  71450. BABYLON.Gamepad = Gamepad;
  71451. var GenericPad = /** @class */ (function (_super) {
  71452. __extends(GenericPad, _super);
  71453. function GenericPad(id, index, browserGamepad) {
  71454. var _this = _super.call(this, id, index, browserGamepad) || this;
  71455. _this.onButtonDownObservable = new BABYLON.Observable();
  71456. _this.onButtonUpObservable = new BABYLON.Observable();
  71457. _this.type = Gamepad.GENERIC;
  71458. _this._buttons = new Array(browserGamepad.buttons.length);
  71459. return _this;
  71460. }
  71461. GenericPad.prototype.onbuttondown = function (callback) {
  71462. this._onbuttondown = callback;
  71463. };
  71464. GenericPad.prototype.onbuttonup = function (callback) {
  71465. this._onbuttonup = callback;
  71466. };
  71467. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71468. if (newValue !== currentValue) {
  71469. if (newValue === 1) {
  71470. if (this._onbuttondown) {
  71471. this._onbuttondown(buttonIndex);
  71472. }
  71473. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71474. }
  71475. if (newValue === 0) {
  71476. if (this._onbuttonup) {
  71477. this._onbuttonup(buttonIndex);
  71478. }
  71479. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71480. }
  71481. }
  71482. return newValue;
  71483. };
  71484. GenericPad.prototype.update = function () {
  71485. _super.prototype.update.call(this);
  71486. for (var index = 0; index < this._buttons.length; index++) {
  71487. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71488. }
  71489. };
  71490. GenericPad.prototype.dispose = function () {
  71491. _super.prototype.dispose.call(this);
  71492. this.onButtonDownObservable.clear();
  71493. this.onButtonUpObservable.clear();
  71494. };
  71495. return GenericPad;
  71496. }(Gamepad));
  71497. BABYLON.GenericPad = GenericPad;
  71498. })(BABYLON || (BABYLON = {}));
  71499. //# sourceMappingURL=babylon.gamepad.js.map
  71500. var BABYLON;
  71501. (function (BABYLON) {
  71502. /**
  71503. * Defines supported buttons for XBox360 compatible gamepads
  71504. */
  71505. var Xbox360Button;
  71506. (function (Xbox360Button) {
  71507. /** A */
  71508. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71509. /** B */
  71510. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71511. /** X */
  71512. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71513. /** Y */
  71514. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71515. /** Start */
  71516. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71517. /** Back */
  71518. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71519. /** Left button */
  71520. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71521. /** Right button */
  71522. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71523. /** Left stick */
  71524. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71525. /** Right stick */
  71526. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71527. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71528. /** Defines values for XBox360 DPad */
  71529. var Xbox360Dpad;
  71530. (function (Xbox360Dpad) {
  71531. /** Up */
  71532. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71533. /** Down */
  71534. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71535. /** Left */
  71536. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71537. /** Right */
  71538. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71539. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71540. /**
  71541. * Defines a XBox360 gamepad
  71542. */
  71543. var Xbox360Pad = /** @class */ (function (_super) {
  71544. __extends(Xbox360Pad, _super);
  71545. /**
  71546. * Creates a new XBox360 gamepad object
  71547. * @param id defines the id of this gamepad
  71548. * @param index defines its index
  71549. * @param gamepad defines the internal HTML gamepad object
  71550. * @param xboxOne defines if it is a XBox One gamepad
  71551. */
  71552. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71553. if (xboxOne === void 0) { xboxOne = false; }
  71554. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71555. _this._leftTrigger = 0;
  71556. _this._rightTrigger = 0;
  71557. /** Observable raised when a button is pressed */
  71558. _this.onButtonDownObservable = new BABYLON.Observable();
  71559. /** Observable raised when a button is released */
  71560. _this.onButtonUpObservable = new BABYLON.Observable();
  71561. /** Observable raised when a pad is pressed */
  71562. _this.onPadDownObservable = new BABYLON.Observable();
  71563. /** Observable raised when a pad is released */
  71564. _this.onPadUpObservable = new BABYLON.Observable();
  71565. _this._buttonA = 0;
  71566. _this._buttonB = 0;
  71567. _this._buttonX = 0;
  71568. _this._buttonY = 0;
  71569. _this._buttonBack = 0;
  71570. _this._buttonStart = 0;
  71571. _this._buttonLB = 0;
  71572. _this._buttonRB = 0;
  71573. _this._buttonLeftStick = 0;
  71574. _this._buttonRightStick = 0;
  71575. _this._dPadUp = 0;
  71576. _this._dPadDown = 0;
  71577. _this._dPadLeft = 0;
  71578. _this._dPadRight = 0;
  71579. _this._isXboxOnePad = false;
  71580. _this.type = BABYLON.Gamepad.XBOX;
  71581. _this._isXboxOnePad = xboxOne;
  71582. return _this;
  71583. }
  71584. /**
  71585. * Defines the callback to call when left trigger is pressed
  71586. * @param callback defines the callback to use
  71587. */
  71588. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71589. this._onlefttriggerchanged = callback;
  71590. };
  71591. /**
  71592. * Defines the callback to call when right trigger is pressed
  71593. * @param callback defines the callback to use
  71594. */
  71595. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71596. this._onrighttriggerchanged = callback;
  71597. };
  71598. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71599. /**
  71600. * Gets or sets left trigger value
  71601. */
  71602. get: function () {
  71603. return this._leftTrigger;
  71604. },
  71605. set: function (newValue) {
  71606. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71607. this._onlefttriggerchanged(newValue);
  71608. }
  71609. this._leftTrigger = newValue;
  71610. },
  71611. enumerable: true,
  71612. configurable: true
  71613. });
  71614. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71615. /**
  71616. * Gets or sets right trigger value
  71617. */
  71618. get: function () {
  71619. return this._rightTrigger;
  71620. },
  71621. set: function (newValue) {
  71622. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71623. this._onrighttriggerchanged(newValue);
  71624. }
  71625. this._rightTrigger = newValue;
  71626. },
  71627. enumerable: true,
  71628. configurable: true
  71629. });
  71630. /**
  71631. * Defines the callback to call when a button is pressed
  71632. * @param callback defines the callback to use
  71633. */
  71634. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71635. this._onbuttondown = callback;
  71636. };
  71637. /**
  71638. * Defines the callback to call when a button is released
  71639. * @param callback defines the callback to use
  71640. */
  71641. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71642. this._onbuttonup = callback;
  71643. };
  71644. /**
  71645. * Defines the callback to call when a pad is pressed
  71646. * @param callback defines the callback to use
  71647. */
  71648. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71649. this._ondpaddown = callback;
  71650. };
  71651. /**
  71652. * Defines the callback to call when a pad is released
  71653. * @param callback defines the callback to use
  71654. */
  71655. Xbox360Pad.prototype.ondpadup = function (callback) {
  71656. this._ondpadup = callback;
  71657. };
  71658. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71659. if (newValue !== currentValue) {
  71660. if (newValue === 1) {
  71661. if (this._onbuttondown) {
  71662. this._onbuttondown(buttonType);
  71663. }
  71664. this.onButtonDownObservable.notifyObservers(buttonType);
  71665. }
  71666. if (newValue === 0) {
  71667. if (this._onbuttonup) {
  71668. this._onbuttonup(buttonType);
  71669. }
  71670. this.onButtonUpObservable.notifyObservers(buttonType);
  71671. }
  71672. }
  71673. return newValue;
  71674. };
  71675. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71676. if (newValue !== currentValue) {
  71677. if (newValue === 1) {
  71678. if (this._ondpaddown) {
  71679. this._ondpaddown(buttonType);
  71680. }
  71681. this.onPadDownObservable.notifyObservers(buttonType);
  71682. }
  71683. if (newValue === 0) {
  71684. if (this._ondpadup) {
  71685. this._ondpadup(buttonType);
  71686. }
  71687. this.onPadUpObservable.notifyObservers(buttonType);
  71688. }
  71689. }
  71690. return newValue;
  71691. };
  71692. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71693. /** Gets or sets value of A button */
  71694. get: function () {
  71695. return this._buttonA;
  71696. },
  71697. set: function (value) {
  71698. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71699. },
  71700. enumerable: true,
  71701. configurable: true
  71702. });
  71703. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71704. /** Gets or sets value of B button */
  71705. get: function () {
  71706. return this._buttonB;
  71707. },
  71708. set: function (value) {
  71709. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71715. /** Gets or sets value of X button */
  71716. get: function () {
  71717. return this._buttonX;
  71718. },
  71719. set: function (value) {
  71720. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71721. },
  71722. enumerable: true,
  71723. configurable: true
  71724. });
  71725. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71726. /** Gets or sets value of Y button */
  71727. get: function () {
  71728. return this._buttonY;
  71729. },
  71730. set: function (value) {
  71731. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71732. },
  71733. enumerable: true,
  71734. configurable: true
  71735. });
  71736. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71737. /** Gets or sets value of Start button */
  71738. get: function () {
  71739. return this._buttonStart;
  71740. },
  71741. set: function (value) {
  71742. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71743. },
  71744. enumerable: true,
  71745. configurable: true
  71746. });
  71747. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71748. /** Gets or sets value of Back button */
  71749. get: function () {
  71750. return this._buttonBack;
  71751. },
  71752. set: function (value) {
  71753. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71754. },
  71755. enumerable: true,
  71756. configurable: true
  71757. });
  71758. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71759. /** Gets or sets value of Left button */
  71760. get: function () {
  71761. return this._buttonLB;
  71762. },
  71763. set: function (value) {
  71764. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71765. },
  71766. enumerable: true,
  71767. configurable: true
  71768. });
  71769. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71770. /** Gets or sets value of Right button */
  71771. get: function () {
  71772. return this._buttonRB;
  71773. },
  71774. set: function (value) {
  71775. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71776. },
  71777. enumerable: true,
  71778. configurable: true
  71779. });
  71780. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71781. /** Gets or sets value of left stick */
  71782. get: function () {
  71783. return this._buttonLeftStick;
  71784. },
  71785. set: function (value) {
  71786. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71787. },
  71788. enumerable: true,
  71789. configurable: true
  71790. });
  71791. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71792. /** Gets or sets value of right stick */
  71793. get: function () {
  71794. return this._buttonRightStick;
  71795. },
  71796. set: function (value) {
  71797. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71798. },
  71799. enumerable: true,
  71800. configurable: true
  71801. });
  71802. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71803. /** Gets or sets value of DPad up */
  71804. get: function () {
  71805. return this._dPadUp;
  71806. },
  71807. set: function (value) {
  71808. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71809. },
  71810. enumerable: true,
  71811. configurable: true
  71812. });
  71813. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71814. /** Gets or sets value of DPad down */
  71815. get: function () {
  71816. return this._dPadDown;
  71817. },
  71818. set: function (value) {
  71819. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71820. },
  71821. enumerable: true,
  71822. configurable: true
  71823. });
  71824. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71825. /** Gets or sets value of DPad left */
  71826. get: function () {
  71827. return this._dPadLeft;
  71828. },
  71829. set: function (value) {
  71830. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71831. },
  71832. enumerable: true,
  71833. configurable: true
  71834. });
  71835. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71836. /** Gets or sets value of DPad right */
  71837. get: function () {
  71838. return this._dPadRight;
  71839. },
  71840. set: function (value) {
  71841. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71842. },
  71843. enumerable: true,
  71844. configurable: true
  71845. });
  71846. /**
  71847. * Force the gamepad to synchronize with device values
  71848. */
  71849. Xbox360Pad.prototype.update = function () {
  71850. _super.prototype.update.call(this);
  71851. if (this._isXboxOnePad) {
  71852. this.buttonA = this.browserGamepad.buttons[0].value;
  71853. this.buttonB = this.browserGamepad.buttons[1].value;
  71854. this.buttonX = this.browserGamepad.buttons[2].value;
  71855. this.buttonY = this.browserGamepad.buttons[3].value;
  71856. this.buttonLB = this.browserGamepad.buttons[4].value;
  71857. this.buttonRB = this.browserGamepad.buttons[5].value;
  71858. this.leftTrigger = this.browserGamepad.axes[2];
  71859. this.rightTrigger = this.browserGamepad.axes[5];
  71860. this.buttonBack = this.browserGamepad.buttons[9].value;
  71861. this.buttonStart = this.browserGamepad.buttons[8].value;
  71862. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71863. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71864. this.dPadUp = this.browserGamepad.buttons[11].value;
  71865. this.dPadDown = this.browserGamepad.buttons[12].value;
  71866. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71867. this.dPadRight = this.browserGamepad.buttons[14].value;
  71868. }
  71869. else {
  71870. this.buttonA = this.browserGamepad.buttons[0].value;
  71871. this.buttonB = this.browserGamepad.buttons[1].value;
  71872. this.buttonX = this.browserGamepad.buttons[2].value;
  71873. this.buttonY = this.browserGamepad.buttons[3].value;
  71874. this.buttonLB = this.browserGamepad.buttons[4].value;
  71875. this.buttonRB = this.browserGamepad.buttons[5].value;
  71876. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71877. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71878. this.buttonBack = this.browserGamepad.buttons[8].value;
  71879. this.buttonStart = this.browserGamepad.buttons[9].value;
  71880. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71881. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71882. this.dPadUp = this.browserGamepad.buttons[12].value;
  71883. this.dPadDown = this.browserGamepad.buttons[13].value;
  71884. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71885. this.dPadRight = this.browserGamepad.buttons[15].value;
  71886. }
  71887. };
  71888. Xbox360Pad.prototype.dispose = function () {
  71889. _super.prototype.dispose.call(this);
  71890. this.onButtonDownObservable.clear();
  71891. this.onButtonUpObservable.clear();
  71892. this.onPadDownObservable.clear();
  71893. this.onPadUpObservable.clear();
  71894. };
  71895. return Xbox360Pad;
  71896. }(BABYLON.Gamepad));
  71897. BABYLON.Xbox360Pad = Xbox360Pad;
  71898. })(BABYLON || (BABYLON = {}));
  71899. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71900. var BABYLON;
  71901. (function (BABYLON) {
  71902. /**
  71903. * Defines the types of pose enabled controllers that are supported
  71904. */
  71905. var PoseEnabledControllerType;
  71906. (function (PoseEnabledControllerType) {
  71907. /**
  71908. * HTC Vive
  71909. */
  71910. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71911. /**
  71912. * Oculus Rift
  71913. */
  71914. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71915. /**
  71916. * Windows mixed reality
  71917. */
  71918. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71919. /**
  71920. * Samsung gear VR
  71921. */
  71922. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71923. /**
  71924. * Google Daydream
  71925. */
  71926. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71927. /**
  71928. * Generic
  71929. */
  71930. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71931. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71932. /**
  71933. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71934. */
  71935. var PoseEnabledControllerHelper = /** @class */ (function () {
  71936. function PoseEnabledControllerHelper() {
  71937. }
  71938. /**
  71939. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71940. * @param vrGamepad the gamepad to initialized
  71941. * @returns a vr controller of the type the gamepad identified as
  71942. */
  71943. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71944. // Oculus Touch
  71945. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71946. return new BABYLON.OculusTouchController(vrGamepad);
  71947. }
  71948. // Windows Mixed Reality controllers
  71949. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71950. return new BABYLON.WindowsMotionController(vrGamepad);
  71951. }
  71952. // HTC Vive
  71953. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71954. return new BABYLON.ViveController(vrGamepad);
  71955. }
  71956. // Samsung/Oculus Gear VR or Oculus Go
  71957. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71958. return new BABYLON.GearVRController(vrGamepad);
  71959. }
  71960. // Google Daydream
  71961. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71962. return new BABYLON.DaydreamController(vrGamepad);
  71963. }
  71964. // Generic
  71965. else {
  71966. return new BABYLON.GenericController(vrGamepad);
  71967. }
  71968. };
  71969. return PoseEnabledControllerHelper;
  71970. }());
  71971. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71972. /**
  71973. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71974. */
  71975. var PoseEnabledController = /** @class */ (function (_super) {
  71976. __extends(PoseEnabledController, _super);
  71977. /**
  71978. * Creates a new PoseEnabledController from a gamepad
  71979. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71980. */
  71981. function PoseEnabledController(browserGamepad) {
  71982. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71983. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71984. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71985. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71986. /**
  71987. * The device position in babylon space
  71988. */
  71989. _this.devicePosition = BABYLON.Vector3.Zero();
  71990. /**
  71991. * The device rotation in babylon space
  71992. */
  71993. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71994. /**
  71995. * The scale factor of the device in babylon space
  71996. */
  71997. _this.deviceScaleFactor = 1;
  71998. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71999. /**
  72000. * Internal, matrix used to convert room space to babylon space
  72001. */
  72002. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72003. /**
  72004. * Node to be used when casting a ray from the controller
  72005. */
  72006. _this._pointingPoseNode = null;
  72007. _this._workingMatrix = BABYLON.Matrix.Identity();
  72008. /**
  72009. * @hidden
  72010. */
  72011. _this._meshAttachedObservable = new BABYLON.Observable();
  72012. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72013. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72014. _this.position = BABYLON.Vector3.Zero();
  72015. _this.rotationQuaternion = new BABYLON.Quaternion();
  72016. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72017. _this._calculatedRotation = new BABYLON.Quaternion();
  72018. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72019. return _this;
  72020. }
  72021. /**
  72022. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72023. */
  72024. PoseEnabledController.prototype.update = function () {
  72025. _super.prototype.update.call(this);
  72026. this._updatePoseAndMesh();
  72027. };
  72028. /**
  72029. * Updates only the pose device and mesh without doing any button event checking
  72030. */
  72031. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72032. var pose = this.browserGamepad.pose;
  72033. this.updateFromDevice(pose);
  72034. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72035. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72036. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72037. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72038. if (this._mesh) {
  72039. this._mesh.position.copyFrom(this.devicePosition);
  72040. if (this._mesh.rotationQuaternion) {
  72041. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72042. }
  72043. }
  72044. };
  72045. /**
  72046. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72047. * @param poseData raw pose fromthe device
  72048. */
  72049. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72050. if (poseData) {
  72051. this.rawPose = poseData;
  72052. if (poseData.position) {
  72053. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72054. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72055. this._deviceRoomPosition.z *= -1;
  72056. }
  72057. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72058. this._calculatedPosition.addInPlace(this.position);
  72059. }
  72060. var pose = this.rawPose;
  72061. if (poseData.orientation && pose.orientation) {
  72062. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72063. if (this._mesh) {
  72064. if (this._mesh.getScene().useRightHandedSystem) {
  72065. this._deviceRoomRotationQuaternion.z *= -1;
  72066. this._deviceRoomRotationQuaternion.w *= -1;
  72067. }
  72068. else {
  72069. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72070. }
  72071. }
  72072. // if the camera is set, rotate to the camera's rotation
  72073. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72074. }
  72075. }
  72076. };
  72077. /**
  72078. * Attaches a mesh to the controller
  72079. * @param mesh the mesh to be attached
  72080. */
  72081. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72082. if (this._mesh) {
  72083. this._mesh.parent = null;
  72084. }
  72085. this._mesh = mesh;
  72086. if (this._poseControlledCamera) {
  72087. this._mesh.parent = this._poseControlledCamera;
  72088. }
  72089. if (!this._mesh.rotationQuaternion) {
  72090. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72091. }
  72092. // 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
  72093. this._updatePoseAndMesh();
  72094. if (this._pointingPoseNode) {
  72095. var parents = [];
  72096. var obj = this._pointingPoseNode;
  72097. while (obj.parent) {
  72098. parents.push(obj.parent);
  72099. obj = obj.parent;
  72100. }
  72101. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72102. }
  72103. this._meshAttachedObservable.notifyObservers(mesh);
  72104. };
  72105. /**
  72106. * Attaches the controllers mesh to a camera
  72107. * @param camera the camera the mesh should be attached to
  72108. */
  72109. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72110. this._poseControlledCamera = camera;
  72111. if (this._mesh) {
  72112. this._mesh.parent = this._poseControlledCamera;
  72113. }
  72114. };
  72115. /**
  72116. * Disposes of the controller
  72117. */
  72118. PoseEnabledController.prototype.dispose = function () {
  72119. if (this._mesh) {
  72120. this._mesh.dispose();
  72121. }
  72122. this._mesh = null;
  72123. _super.prototype.dispose.call(this);
  72124. };
  72125. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72126. /**
  72127. * The mesh that is attached to the controller
  72128. */
  72129. get: function () {
  72130. return this._mesh;
  72131. },
  72132. enumerable: true,
  72133. configurable: true
  72134. });
  72135. /**
  72136. * Gets the ray of the controller in the direction the controller is pointing
  72137. * @param length the length the resulting ray should be
  72138. * @returns a ray in the direction the controller is pointing
  72139. */
  72140. PoseEnabledController.prototype.getForwardRay = function (length) {
  72141. if (length === void 0) { length = 100; }
  72142. if (!this.mesh) {
  72143. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72144. }
  72145. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72146. var origin = m.getTranslation();
  72147. var forward = new BABYLON.Vector3(0, 0, -1);
  72148. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72149. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72150. return new BABYLON.Ray(origin, direction, length);
  72151. };
  72152. /**
  72153. * Name of the child mesh that can be used to cast a ray from the controller
  72154. */
  72155. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72156. return PoseEnabledController;
  72157. }(BABYLON.Gamepad));
  72158. BABYLON.PoseEnabledController = PoseEnabledController;
  72159. })(BABYLON || (BABYLON = {}));
  72160. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72161. var BABYLON;
  72162. (function (BABYLON) {
  72163. /**
  72164. * Defines the WebVRController object that represents controllers tracked in 3D space
  72165. */
  72166. var WebVRController = /** @class */ (function (_super) {
  72167. __extends(WebVRController, _super);
  72168. /**
  72169. * Creates a new WebVRController from a gamepad
  72170. * @param vrGamepad the gamepad that the WebVRController should be created from
  72171. */
  72172. function WebVRController(vrGamepad) {
  72173. var _this = _super.call(this, vrGamepad) || this;
  72174. // Observables
  72175. /**
  72176. * Fired when the trigger state has changed
  72177. */
  72178. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72179. /**
  72180. * Fired when the main button state has changed
  72181. */
  72182. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72183. /**
  72184. * Fired when the secondary button state has changed
  72185. */
  72186. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72187. /**
  72188. * Fired when the pad state has changed
  72189. */
  72190. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72191. /**
  72192. * Fired when controllers stick values have changed
  72193. */
  72194. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72195. /**
  72196. * X and Y axis corrisponding to the controllers joystick
  72197. */
  72198. _this.pad = { x: 0, y: 0 };
  72199. // avoid GC, store state in a tmp object
  72200. _this._changes = {
  72201. pressChanged: false,
  72202. touchChanged: false,
  72203. valueChanged: false,
  72204. changed: false
  72205. };
  72206. _this._buttons = new Array(vrGamepad.buttons.length);
  72207. _this.hand = vrGamepad.hand;
  72208. return _this;
  72209. }
  72210. /**
  72211. * Fired when a controller button's state has changed
  72212. * @param callback the callback containing the button that was modified
  72213. */
  72214. WebVRController.prototype.onButtonStateChange = function (callback) {
  72215. this._onButtonStateChange = callback;
  72216. };
  72217. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72218. /**
  72219. * The default controller model for the controller
  72220. */
  72221. get: function () {
  72222. return this._defaultModel;
  72223. },
  72224. enumerable: true,
  72225. configurable: true
  72226. });
  72227. /**
  72228. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72229. */
  72230. WebVRController.prototype.update = function () {
  72231. _super.prototype.update.call(this);
  72232. for (var index = 0; index < this._buttons.length; index++) {
  72233. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72234. }
  72235. ;
  72236. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72237. this.pad.x = this.leftStick.x;
  72238. this.pad.y = this.leftStick.y;
  72239. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72240. }
  72241. };
  72242. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72243. if (!newState) {
  72244. newState = {
  72245. pressed: false,
  72246. touched: false,
  72247. value: 0
  72248. };
  72249. }
  72250. if (!currentState) {
  72251. this._buttons[buttonIndex] = {
  72252. pressed: newState.pressed,
  72253. touched: newState.touched,
  72254. value: newState.value
  72255. };
  72256. return;
  72257. }
  72258. this._checkChanges(newState, currentState);
  72259. if (this._changes.changed) {
  72260. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72261. this._handleButtonChange(buttonIndex, newState, this._changes);
  72262. }
  72263. this._buttons[buttonIndex].pressed = newState.pressed;
  72264. this._buttons[buttonIndex].touched = newState.touched;
  72265. // oculus triggers are never 0, thou not touched.
  72266. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72267. };
  72268. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72269. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72270. this._changes.touchChanged = newState.touched !== currentState.touched;
  72271. this._changes.valueChanged = newState.value !== currentState.value;
  72272. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72273. return this._changes;
  72274. };
  72275. /**
  72276. * Disposes of th webVRCOntroller
  72277. */
  72278. WebVRController.prototype.dispose = function () {
  72279. _super.prototype.dispose.call(this);
  72280. this.onTriggerStateChangedObservable.clear();
  72281. this.onMainButtonStateChangedObservable.clear();
  72282. this.onSecondaryButtonStateChangedObservable.clear();
  72283. this.onPadStateChangedObservable.clear();
  72284. this.onPadValuesChangedObservable.clear();
  72285. };
  72286. return WebVRController;
  72287. }(BABYLON.PoseEnabledController));
  72288. BABYLON.WebVRController = WebVRController;
  72289. })(BABYLON || (BABYLON = {}));
  72290. //# sourceMappingURL=babylon.webVRController.js.map
  72291. var BABYLON;
  72292. (function (BABYLON) {
  72293. /**
  72294. * Oculus Touch Controller
  72295. */
  72296. var OculusTouchController = /** @class */ (function (_super) {
  72297. __extends(OculusTouchController, _super);
  72298. /**
  72299. * Creates a new OculusTouchController from a gamepad
  72300. * @param vrGamepad the gamepad that the controller should be created from
  72301. */
  72302. function OculusTouchController(vrGamepad) {
  72303. var _this = _super.call(this, vrGamepad) || this;
  72304. /**
  72305. * Fired when the secondary trigger on this controller is modified
  72306. */
  72307. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72308. /**
  72309. * Fired when the thumb rest on this controller is modified
  72310. */
  72311. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72312. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72313. return _this;
  72314. }
  72315. /**
  72316. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72317. * @param scene scene in which to add meshes
  72318. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72319. */
  72320. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72321. var _this = this;
  72322. var meshName;
  72323. // Hand
  72324. if (this.hand === 'left') {
  72325. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72326. }
  72327. else { // Right is the default if no hand is specified
  72328. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72329. }
  72330. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72331. /*
  72332. Parent Mesh name: oculus_touch_left
  72333. - body
  72334. - trigger
  72335. - thumbstick
  72336. - grip
  72337. - button_y
  72338. - button_x
  72339. - button_enter
  72340. */
  72341. _this._defaultModel = newMeshes[1];
  72342. _this.attachToMesh(_this._defaultModel);
  72343. if (meshLoaded) {
  72344. meshLoaded(_this._defaultModel);
  72345. }
  72346. });
  72347. };
  72348. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72349. /**
  72350. * Fired when the A button on this controller is modified
  72351. */
  72352. get: function () {
  72353. if (this.hand === 'right') {
  72354. return this.onMainButtonStateChangedObservable;
  72355. }
  72356. else {
  72357. throw new Error('No A button on left hand');
  72358. }
  72359. },
  72360. enumerable: true,
  72361. configurable: true
  72362. });
  72363. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72364. /**
  72365. * Fired when the B button on this controller is modified
  72366. */
  72367. get: function () {
  72368. if (this.hand === 'right') {
  72369. return this.onSecondaryButtonStateChangedObservable;
  72370. }
  72371. else {
  72372. throw new Error('No B button on left hand');
  72373. }
  72374. },
  72375. enumerable: true,
  72376. configurable: true
  72377. });
  72378. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72379. /**
  72380. * Fired when the X button on this controller is modified
  72381. */
  72382. get: function () {
  72383. if (this.hand === 'left') {
  72384. return this.onMainButtonStateChangedObservable;
  72385. }
  72386. else {
  72387. throw new Error('No X button on right hand');
  72388. }
  72389. },
  72390. enumerable: true,
  72391. configurable: true
  72392. });
  72393. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72394. /**
  72395. * Fired when the Y button on this controller is modified
  72396. */
  72397. get: function () {
  72398. if (this.hand === 'left') {
  72399. return this.onSecondaryButtonStateChangedObservable;
  72400. }
  72401. else {
  72402. throw new Error('No Y button on right hand');
  72403. }
  72404. },
  72405. enumerable: true,
  72406. configurable: true
  72407. });
  72408. /**
  72409. * Called once for each button that changed state since the last frame
  72410. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72411. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72412. * 2) secondary trigger (same)
  72413. * 3) A (right) X (left), touch, pressed = value
  72414. * 4) B / Y
  72415. * 5) thumb rest
  72416. * @param buttonIdx Which button index changed
  72417. * @param state New state of the button
  72418. * @param changes Which properties on the state changed since last frame
  72419. */
  72420. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72421. var notifyObject = state; //{ state: state, changes: changes };
  72422. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72423. switch (buttonIdx) {
  72424. case 0:
  72425. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72426. return;
  72427. case 1: // index trigger
  72428. if (this._defaultModel) {
  72429. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72430. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72431. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72432. }
  72433. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72434. return;
  72435. case 2: // secondary trigger
  72436. if (this._defaultModel) {
  72437. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72438. }
  72439. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72440. return;
  72441. case 3:
  72442. if (this._defaultModel) {
  72443. if (notifyObject.pressed) {
  72444. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72445. }
  72446. else {
  72447. (this._defaultModel.getChildren()[1]).position.y = 0;
  72448. }
  72449. }
  72450. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72451. return;
  72452. case 4:
  72453. if (this._defaultModel) {
  72454. if (notifyObject.pressed) {
  72455. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72456. }
  72457. else {
  72458. (this._defaultModel.getChildren()[2]).position.y = 0;
  72459. }
  72460. }
  72461. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72462. return;
  72463. case 5:
  72464. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72465. return;
  72466. }
  72467. };
  72468. /**
  72469. * Base Url for the controller model.
  72470. */
  72471. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72472. /**
  72473. * File name for the left controller model.
  72474. */
  72475. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72476. /**
  72477. * File name for the right controller model.
  72478. */
  72479. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72480. return OculusTouchController;
  72481. }(BABYLON.WebVRController));
  72482. BABYLON.OculusTouchController = OculusTouchController;
  72483. })(BABYLON || (BABYLON = {}));
  72484. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72485. var BABYLON;
  72486. (function (BABYLON) {
  72487. /**
  72488. * Vive Controller
  72489. */
  72490. var ViveController = /** @class */ (function (_super) {
  72491. __extends(ViveController, _super);
  72492. /**
  72493. * Creates a new ViveController from a gamepad
  72494. * @param vrGamepad the gamepad that the controller should be created from
  72495. */
  72496. function ViveController(vrGamepad) {
  72497. var _this = _super.call(this, vrGamepad) || this;
  72498. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72499. _this._invertLeftStickY = true;
  72500. return _this;
  72501. }
  72502. /**
  72503. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72504. * @param scene scene in which to add meshes
  72505. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72506. */
  72507. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72508. var _this = this;
  72509. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72510. /*
  72511. Parent Mesh name: ViveWand
  72512. - body
  72513. - r_gripper
  72514. - l_gripper
  72515. - menu_button
  72516. - system_button
  72517. - trackpad
  72518. - trigger
  72519. - LED
  72520. */
  72521. _this._defaultModel = newMeshes[1];
  72522. _this.attachToMesh(_this._defaultModel);
  72523. if (meshLoaded) {
  72524. meshLoaded(_this._defaultModel);
  72525. }
  72526. });
  72527. };
  72528. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72529. /**
  72530. * Fired when the left button on this controller is modified
  72531. */
  72532. get: function () {
  72533. return this.onMainButtonStateChangedObservable;
  72534. },
  72535. enumerable: true,
  72536. configurable: true
  72537. });
  72538. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72539. /**
  72540. * Fired when the right button on this controller is modified
  72541. */
  72542. get: function () {
  72543. return this.onMainButtonStateChangedObservable;
  72544. },
  72545. enumerable: true,
  72546. configurable: true
  72547. });
  72548. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72549. /**
  72550. * Fired when the menu button on this controller is modified
  72551. */
  72552. get: function () {
  72553. return this.onSecondaryButtonStateChangedObservable;
  72554. },
  72555. enumerable: true,
  72556. configurable: true
  72557. });
  72558. /**
  72559. * Called once for each button that changed state since the last frame
  72560. * Vive mapping:
  72561. * 0: touchpad
  72562. * 1: trigger
  72563. * 2: left AND right buttons
  72564. * 3: menu button
  72565. * @param buttonIdx Which button index changed
  72566. * @param state New state of the button
  72567. * @param changes Which properties on the state changed since last frame
  72568. */
  72569. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72570. var notifyObject = state; //{ state: state, changes: changes };
  72571. switch (buttonIdx) {
  72572. case 0:
  72573. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72574. return;
  72575. case 1: // index trigger
  72576. if (this._defaultModel) {
  72577. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72578. }
  72579. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72580. return;
  72581. case 2: // left AND right button
  72582. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72583. return;
  72584. case 3:
  72585. if (this._defaultModel) {
  72586. if (notifyObject.pressed) {
  72587. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72588. }
  72589. else {
  72590. (this._defaultModel.getChildren()[2]).position.y = 0;
  72591. }
  72592. }
  72593. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72594. return;
  72595. }
  72596. };
  72597. /**
  72598. * Base Url for the controller model.
  72599. */
  72600. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72601. /**
  72602. * File name for the controller model.
  72603. */
  72604. ViveController.MODEL_FILENAME = 'wand.babylon';
  72605. return ViveController;
  72606. }(BABYLON.WebVRController));
  72607. BABYLON.ViveController = ViveController;
  72608. })(BABYLON || (BABYLON = {}));
  72609. //# sourceMappingURL=babylon.viveController.js.map
  72610. var BABYLON;
  72611. (function (BABYLON) {
  72612. /**
  72613. * Generic Controller
  72614. */
  72615. var GenericController = /** @class */ (function (_super) {
  72616. __extends(GenericController, _super);
  72617. /**
  72618. * Creates a new GenericController from a gamepad
  72619. * @param vrGamepad the gamepad that the controller should be created from
  72620. */
  72621. function GenericController(vrGamepad) {
  72622. return _super.call(this, vrGamepad) || this;
  72623. }
  72624. /**
  72625. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72626. * @param scene scene in which to add meshes
  72627. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72628. */
  72629. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72630. var _this = this;
  72631. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72632. _this._defaultModel = newMeshes[1];
  72633. _this.attachToMesh(_this._defaultModel);
  72634. if (meshLoaded) {
  72635. meshLoaded(_this._defaultModel);
  72636. }
  72637. });
  72638. };
  72639. /**
  72640. * Called once for each button that changed state since the last frame
  72641. * @param buttonIdx Which button index changed
  72642. * @param state New state of the button
  72643. * @param changes Which properties on the state changed since last frame
  72644. */
  72645. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72646. console.log("Button id: " + buttonIdx + "state: ");
  72647. console.dir(state);
  72648. };
  72649. /**
  72650. * Base Url for the controller model.
  72651. */
  72652. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72653. /**
  72654. * File name for the controller model.
  72655. */
  72656. GenericController.MODEL_FILENAME = 'generic.babylon';
  72657. return GenericController;
  72658. }(BABYLON.WebVRController));
  72659. BABYLON.GenericController = GenericController;
  72660. })(BABYLON || (BABYLON = {}));
  72661. //# sourceMappingURL=babylon.genericController.js.map
  72662. var BABYLON;
  72663. (function (BABYLON) {
  72664. /**
  72665. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72666. */
  72667. var LoadedMeshInfo = /** @class */ (function () {
  72668. function LoadedMeshInfo() {
  72669. /**
  72670. * Map of the button meshes contained in the controller
  72671. */
  72672. this.buttonMeshes = {};
  72673. /**
  72674. * Map of the axis meshes contained in the controller
  72675. */
  72676. this.axisMeshes = {};
  72677. }
  72678. return LoadedMeshInfo;
  72679. }());
  72680. /**
  72681. * Defines the WindowsMotionController object that the state of the windows motion controller
  72682. */
  72683. var WindowsMotionController = /** @class */ (function (_super) {
  72684. __extends(WindowsMotionController, _super);
  72685. /**
  72686. * Creates a new WindowsMotionController from a gamepad
  72687. * @param vrGamepad the gamepad that the controller should be created from
  72688. */
  72689. function WindowsMotionController(vrGamepad) {
  72690. var _this = _super.call(this, vrGamepad) || this;
  72691. _this._mapping = {
  72692. // Semantic button names
  72693. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72694. // A mapping of the button name to glTF model node name
  72695. // that should be transformed by button value.
  72696. buttonMeshNames: {
  72697. 'trigger': 'SELECT',
  72698. 'menu': 'MENU',
  72699. 'grip': 'GRASP',
  72700. 'thumbstick': 'THUMBSTICK_PRESS',
  72701. 'trackpad': 'TOUCHPAD_PRESS'
  72702. },
  72703. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72704. buttonObservableNames: {
  72705. 'trigger': 'onTriggerStateChangedObservable',
  72706. 'menu': 'onSecondaryButtonStateChangedObservable',
  72707. 'grip': 'onMainButtonStateChangedObservable',
  72708. 'thumbstick': 'onPadStateChangedObservable',
  72709. 'trackpad': 'onTrackpadChangedObservable'
  72710. },
  72711. // A mapping of the axis name to glTF model node name
  72712. // that should be transformed by axis value.
  72713. // This array mirrors the browserGamepad.axes array, such that
  72714. // the mesh corresponding to axis 0 is in this array index 0.
  72715. axisMeshNames: [
  72716. 'THUMBSTICK_X',
  72717. 'THUMBSTICK_Y',
  72718. 'TOUCHPAD_TOUCH_X',
  72719. 'TOUCHPAD_TOUCH_Y'
  72720. ],
  72721. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72722. };
  72723. /**
  72724. * Fired when the trackpad on this controller is clicked
  72725. */
  72726. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72727. /**
  72728. * Fired when the trackpad on this controller is modified
  72729. */
  72730. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72731. /**
  72732. * The current x and y values of this controller's trackpad
  72733. */
  72734. _this.trackpad = { x: 0, y: 0 };
  72735. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72736. _this._loadedMeshInfo = null;
  72737. return _this;
  72738. }
  72739. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72740. /**
  72741. * Fired when the trigger on this controller is modified
  72742. */
  72743. get: function () {
  72744. return this.onTriggerStateChangedObservable;
  72745. },
  72746. enumerable: true,
  72747. configurable: true
  72748. });
  72749. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72750. /**
  72751. * Fired when the menu button on this controller is modified
  72752. */
  72753. get: function () {
  72754. return this.onSecondaryButtonStateChangedObservable;
  72755. },
  72756. enumerable: true,
  72757. configurable: true
  72758. });
  72759. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72760. /**
  72761. * Fired when the grip button on this controller is modified
  72762. */
  72763. get: function () {
  72764. return this.onMainButtonStateChangedObservable;
  72765. },
  72766. enumerable: true,
  72767. configurable: true
  72768. });
  72769. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72770. /**
  72771. * Fired when the thumbstick button on this controller is modified
  72772. */
  72773. get: function () {
  72774. return this.onPadStateChangedObservable;
  72775. },
  72776. enumerable: true,
  72777. configurable: true
  72778. });
  72779. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72780. /**
  72781. * Fired when the touchpad button on this controller is modified
  72782. */
  72783. get: function () {
  72784. return this.onTrackpadChangedObservable;
  72785. },
  72786. enumerable: true,
  72787. configurable: true
  72788. });
  72789. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72790. /**
  72791. * Fired when the touchpad values on this controller are modified
  72792. */
  72793. get: function () {
  72794. return this.onTrackpadValuesChangedObservable;
  72795. },
  72796. enumerable: true,
  72797. configurable: true
  72798. });
  72799. WindowsMotionController.prototype._updateTrackpad = function () {
  72800. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72801. this.trackpad.x = this.browserGamepad["axes"][2];
  72802. this.trackpad.y = this.browserGamepad["axes"][3];
  72803. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72804. }
  72805. };
  72806. /**
  72807. * Called once per frame by the engine.
  72808. */
  72809. WindowsMotionController.prototype.update = function () {
  72810. _super.prototype.update.call(this);
  72811. if (this.browserGamepad.axes) {
  72812. this._updateTrackpad();
  72813. // Only need to animate axes if there is a loaded mesh
  72814. if (this._loadedMeshInfo) {
  72815. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72816. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72817. }
  72818. }
  72819. }
  72820. };
  72821. /**
  72822. * Called once for each button that changed state since the last frame
  72823. * @param buttonIdx Which button index changed
  72824. * @param state New state of the button
  72825. * @param changes Which properties on the state changed since last frame
  72826. */
  72827. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72828. var buttonName = this._mapping.buttons[buttonIdx];
  72829. if (!buttonName) {
  72830. return;
  72831. }
  72832. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72833. this._updateTrackpad();
  72834. // Only emit events for buttons that we know how to map from index to name
  72835. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72836. if (observable) {
  72837. observable.notifyObservers(state);
  72838. }
  72839. this._lerpButtonTransform(buttonName, state.value);
  72840. };
  72841. /**
  72842. * Moves the buttons on the controller mesh based on their current state
  72843. * @param buttonName the name of the button to move
  72844. * @param buttonValue the value of the button which determines the buttons new position
  72845. */
  72846. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72847. // If there is no loaded mesh, there is nothing to transform.
  72848. if (!this._loadedMeshInfo) {
  72849. return;
  72850. }
  72851. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72852. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72853. return;
  72854. }
  72855. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72856. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72857. };
  72858. /**
  72859. * Moves the axis on the controller mesh based on its current state
  72860. * @param axis the index of the axis
  72861. * @param axisValue the value of the axis which determines the meshes new position
  72862. * @hidden
  72863. */
  72864. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72865. if (!this._loadedMeshInfo) {
  72866. return;
  72867. }
  72868. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72869. if (!meshInfo) {
  72870. return;
  72871. }
  72872. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72873. return;
  72874. }
  72875. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72876. var lerpValue = axisValue * 0.5 + 0.5;
  72877. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72878. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72879. };
  72880. /**
  72881. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72882. * @param scene scene in which to add meshes
  72883. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72884. */
  72885. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72886. var _this = this;
  72887. if (forceDefault === void 0) { forceDefault = false; }
  72888. var path;
  72889. var filename;
  72890. // Checking if GLB loader is present
  72891. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72892. // Determine the device specific folder based on the ID suffix
  72893. var device = 'default';
  72894. if (this.id && !forceDefault) {
  72895. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72896. device = ((match && match[0]) || device);
  72897. }
  72898. // Hand
  72899. if (this.hand === 'left') {
  72900. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72901. }
  72902. else { // Right is the default if no hand is specified
  72903. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72904. }
  72905. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72906. }
  72907. else {
  72908. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72909. path = BABYLON.GenericController.MODEL_BASE_URL;
  72910. filename = BABYLON.GenericController.MODEL_FILENAME;
  72911. }
  72912. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72913. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72914. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72915. if (!_this._loadedMeshInfo) {
  72916. return;
  72917. }
  72918. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72919. _this.attachToMesh(_this._defaultModel);
  72920. if (meshLoaded) {
  72921. meshLoaded(_this._defaultModel);
  72922. }
  72923. }, null, function (scene, message) {
  72924. BABYLON.Tools.Log(message);
  72925. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72926. if (!forceDefault) {
  72927. _this.initControllerMesh(scene, meshLoaded, true);
  72928. }
  72929. });
  72930. };
  72931. /**
  72932. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72933. * can be transformed by button presses and axes values, based on this._mapping.
  72934. *
  72935. * @param scene scene in which the meshes exist
  72936. * @param meshes list of meshes that make up the controller model to process
  72937. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72938. */
  72939. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72940. var loadedMeshInfo = null;
  72941. // Create a new mesh to contain the glTF hierarchy
  72942. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72943. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72944. var childMesh = null;
  72945. for (var i = 0; i < meshes.length; i++) {
  72946. var mesh = meshes[i];
  72947. if (!mesh.parent) {
  72948. // Exclude controller meshes from picking results
  72949. mesh.isPickable = false;
  72950. // Handle root node, attach to the new parentMesh
  72951. childMesh = mesh;
  72952. break;
  72953. }
  72954. }
  72955. if (childMesh) {
  72956. childMesh.setParent(parentMesh);
  72957. // Create our mesh info. Note that this method will always return non-null.
  72958. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72959. }
  72960. else {
  72961. BABYLON.Tools.Warn('Could not find root node in model file.');
  72962. }
  72963. return loadedMeshInfo;
  72964. };
  72965. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72966. var loadedMeshInfo = new LoadedMeshInfo();
  72967. var i;
  72968. loadedMeshInfo.rootNode = rootNode;
  72969. // Reset the caches
  72970. loadedMeshInfo.buttonMeshes = {};
  72971. loadedMeshInfo.axisMeshes = {};
  72972. // Button Meshes
  72973. for (i = 0; i < this._mapping.buttons.length; i++) {
  72974. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72975. if (!buttonMeshName) {
  72976. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72977. continue;
  72978. }
  72979. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72980. if (!buttonMesh) {
  72981. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72982. continue;
  72983. }
  72984. var buttonMeshInfo = {
  72985. index: i,
  72986. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72987. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72988. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72989. };
  72990. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72991. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72992. }
  72993. else {
  72994. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72995. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72996. '(VALUE: ' + !!buttonMeshInfo.value +
  72997. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72998. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72999. ')');
  73000. }
  73001. }
  73002. // Axis Meshes
  73003. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73004. var axisMeshName = this._mapping.axisMeshNames[i];
  73005. if (!axisMeshName) {
  73006. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73007. continue;
  73008. }
  73009. var axisMesh = getChildByName(rootNode, axisMeshName);
  73010. if (!axisMesh) {
  73011. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73012. continue;
  73013. }
  73014. var axisMeshInfo = {
  73015. index: i,
  73016. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73017. min: getImmediateChildByName(axisMesh, 'MIN'),
  73018. max: getImmediateChildByName(axisMesh, 'MAX')
  73019. };
  73020. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73021. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73022. }
  73023. else {
  73024. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73025. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73026. '(VALUE: ' + !!axisMeshInfo.value +
  73027. ', MIN: ' + !!axisMeshInfo.min +
  73028. ', MAX:' + !!axisMeshInfo.max +
  73029. ')');
  73030. }
  73031. }
  73032. // Pointing Ray
  73033. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73034. if (!loadedMeshInfo.pointingPoseNode) {
  73035. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73036. }
  73037. else {
  73038. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73039. }
  73040. return loadedMeshInfo;
  73041. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73042. function getChildByName(node, name) {
  73043. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73044. }
  73045. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73046. function getImmediateChildByName(node, name) {
  73047. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73048. }
  73049. };
  73050. /**
  73051. * Gets the ray of the controller in the direction the controller is pointing
  73052. * @param length the length the resulting ray should be
  73053. * @returns a ray in the direction the controller is pointing
  73054. */
  73055. WindowsMotionController.prototype.getForwardRay = function (length) {
  73056. if (length === void 0) { length = 100; }
  73057. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73058. return _super.prototype.getForwardRay.call(this, length);
  73059. }
  73060. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73061. var origin = m.getTranslation();
  73062. var forward = new BABYLON.Vector3(0, 0, -1);
  73063. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73064. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73065. return new BABYLON.Ray(origin, direction, length);
  73066. };
  73067. /**
  73068. * Disposes of the controller
  73069. */
  73070. WindowsMotionController.prototype.dispose = function () {
  73071. _super.prototype.dispose.call(this);
  73072. this.onTrackpadChangedObservable.clear();
  73073. };
  73074. /**
  73075. * The base url used to load the left and right controller models
  73076. */
  73077. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73078. /**
  73079. * The name of the left controller model file
  73080. */
  73081. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73082. /**
  73083. * The name of the right controller model file
  73084. */
  73085. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73086. /**
  73087. * The controller name prefix for this controller type
  73088. */
  73089. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73090. /**
  73091. * The controller id pattern for this controller type
  73092. */
  73093. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73094. return WindowsMotionController;
  73095. }(BABYLON.WebVRController));
  73096. BABYLON.WindowsMotionController = WindowsMotionController;
  73097. })(BABYLON || (BABYLON = {}));
  73098. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73099. var BABYLON;
  73100. (function (BABYLON) {
  73101. /**
  73102. * Gear VR Controller
  73103. */
  73104. var GearVRController = /** @class */ (function (_super) {
  73105. __extends(GearVRController, _super);
  73106. /**
  73107. * Creates a new GearVRController from a gamepad
  73108. * @param vrGamepad the gamepad that the controller should be created from
  73109. */
  73110. function GearVRController(vrGamepad) {
  73111. var _this = _super.call(this, vrGamepad) || this;
  73112. _this._buttonIndexToObservableNameMap = [
  73113. 'onTrackpadChangedObservable',
  73114. 'onTriggerStateChangedObservable' // Trigger
  73115. ];
  73116. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73117. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73118. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  73119. return _this;
  73120. }
  73121. /**
  73122. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73123. * @param scene scene in which to add meshes
  73124. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73125. */
  73126. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73127. var _this = this;
  73128. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73129. _this._defaultModel = newMeshes[1];
  73130. _this.attachToMesh(_this._defaultModel);
  73131. if (meshLoaded) {
  73132. meshLoaded(_this._defaultModel);
  73133. }
  73134. });
  73135. };
  73136. /**
  73137. * Called once for each button that changed state since the last frame
  73138. * @param buttonIdx Which button index changed
  73139. * @param state New state of the button
  73140. * @param changes Which properties on the state changed since last frame
  73141. */
  73142. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73143. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73144. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73145. // Only emit events for buttons that we know how to map from index to observable
  73146. var observable = this[observableName];
  73147. if (observable) {
  73148. observable.notifyObservers(state);
  73149. }
  73150. }
  73151. };
  73152. /**
  73153. * Base Url for the controller model.
  73154. */
  73155. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73156. /**
  73157. * File name for the controller model.
  73158. */
  73159. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73160. /**
  73161. * Gamepad Id prefix used to identify this controller.
  73162. */
  73163. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73164. return GearVRController;
  73165. }(BABYLON.WebVRController));
  73166. BABYLON.GearVRController = GearVRController;
  73167. })(BABYLON || (BABYLON = {}));
  73168. //# sourceMappingURL=babylon.gearVRController.js.map
  73169. var BABYLON;
  73170. (function (BABYLON) {
  73171. /**
  73172. * Google Daydream controller
  73173. */
  73174. var DaydreamController = /** @class */ (function (_super) {
  73175. __extends(DaydreamController, _super);
  73176. /**
  73177. * Creates a new DaydreamController from a gamepad
  73178. * @param vrGamepad the gamepad that the controller should be created from
  73179. */
  73180. function DaydreamController(vrGamepad) {
  73181. var _this = _super.call(this, vrGamepad) || this;
  73182. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73183. return _this;
  73184. }
  73185. /**
  73186. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73187. * @param scene scene in which to add meshes
  73188. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73189. */
  73190. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73191. var _this = this;
  73192. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73193. _this._defaultModel = newMeshes[1];
  73194. _this.attachToMesh(_this._defaultModel);
  73195. if (meshLoaded) {
  73196. meshLoaded(_this._defaultModel);
  73197. }
  73198. });
  73199. };
  73200. /**
  73201. * Called once for each button that changed state since the last frame
  73202. * @param buttonIdx Which button index changed
  73203. * @param state New state of the button
  73204. * @param changes Which properties on the state changed since last frame
  73205. */
  73206. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73207. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73208. if (buttonIdx === 0) {
  73209. var observable = this.onTriggerStateChangedObservable;
  73210. if (observable) {
  73211. observable.notifyObservers(state);
  73212. }
  73213. }
  73214. else {
  73215. // If the app or home buttons are ever made available
  73216. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73217. }
  73218. };
  73219. /**
  73220. * Base Url for the controller model.
  73221. */
  73222. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73223. /**
  73224. * File name for the controller model.
  73225. */
  73226. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73227. /**
  73228. * Gamepad Id prefix used to identify Daydream Controller.
  73229. */
  73230. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73231. return DaydreamController;
  73232. }(BABYLON.WebVRController));
  73233. BABYLON.DaydreamController = DaydreamController;
  73234. })(BABYLON || (BABYLON = {}));
  73235. //# sourceMappingURL=babylon.daydreamController.js.map
  73236. var BABYLON;
  73237. (function (BABYLON) {
  73238. var FollowCamera = /** @class */ (function (_super) {
  73239. __extends(FollowCamera, _super);
  73240. function FollowCamera(name, position, scene, lockedTarget) {
  73241. if (lockedTarget === void 0) { lockedTarget = null; }
  73242. var _this = _super.call(this, name, position, scene) || this;
  73243. _this.radius = 12;
  73244. _this.rotationOffset = 0;
  73245. _this.heightOffset = 4;
  73246. _this.cameraAcceleration = 0.05;
  73247. _this.maxCameraSpeed = 20;
  73248. _this.lockedTarget = lockedTarget;
  73249. return _this;
  73250. }
  73251. FollowCamera.prototype.getRadians = function (degrees) {
  73252. return degrees * Math.PI / 180;
  73253. };
  73254. FollowCamera.prototype.follow = function (cameraTarget) {
  73255. if (!cameraTarget)
  73256. return;
  73257. var yRotation;
  73258. if (cameraTarget.rotationQuaternion) {
  73259. var rotMatrix = new BABYLON.Matrix();
  73260. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73261. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73262. }
  73263. else {
  73264. yRotation = cameraTarget.rotation.y;
  73265. }
  73266. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73267. var targetPosition = cameraTarget.getAbsolutePosition();
  73268. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73269. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73270. var dx = targetX - this.position.x;
  73271. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73272. var dz = (targetZ) - this.position.z;
  73273. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73274. var vy = dy * this.cameraAcceleration;
  73275. var vz = dz * this.cameraAcceleration * 2;
  73276. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73277. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73278. }
  73279. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73280. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73281. }
  73282. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73283. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73284. }
  73285. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73286. this.setTarget(targetPosition);
  73287. };
  73288. FollowCamera.prototype._checkInputs = function () {
  73289. _super.prototype._checkInputs.call(this);
  73290. if (this.lockedTarget) {
  73291. this.follow(this.lockedTarget);
  73292. }
  73293. };
  73294. FollowCamera.prototype.getClassName = function () {
  73295. return "FollowCamera";
  73296. };
  73297. __decorate([
  73298. BABYLON.serialize()
  73299. ], FollowCamera.prototype, "radius", void 0);
  73300. __decorate([
  73301. BABYLON.serialize()
  73302. ], FollowCamera.prototype, "rotationOffset", void 0);
  73303. __decorate([
  73304. BABYLON.serialize()
  73305. ], FollowCamera.prototype, "heightOffset", void 0);
  73306. __decorate([
  73307. BABYLON.serialize()
  73308. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73309. __decorate([
  73310. BABYLON.serialize()
  73311. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73312. __decorate([
  73313. BABYLON.serializeAsMeshReference("lockedTargetId")
  73314. ], FollowCamera.prototype, "lockedTarget", void 0);
  73315. return FollowCamera;
  73316. }(BABYLON.TargetCamera));
  73317. BABYLON.FollowCamera = FollowCamera;
  73318. var ArcFollowCamera = /** @class */ (function (_super) {
  73319. __extends(ArcFollowCamera, _super);
  73320. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73321. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73322. _this.alpha = alpha;
  73323. _this.beta = beta;
  73324. _this.radius = radius;
  73325. _this.target = target;
  73326. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73327. _this.follow();
  73328. return _this;
  73329. }
  73330. ArcFollowCamera.prototype.follow = function () {
  73331. if (!this.target) {
  73332. return;
  73333. }
  73334. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73335. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73336. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73337. var targetPosition = this.target.getAbsolutePosition();
  73338. this.position = targetPosition.add(this._cartesianCoordinates);
  73339. this.setTarget(targetPosition);
  73340. };
  73341. ArcFollowCamera.prototype._checkInputs = function () {
  73342. _super.prototype._checkInputs.call(this);
  73343. this.follow();
  73344. };
  73345. ArcFollowCamera.prototype.getClassName = function () {
  73346. return "ArcFollowCamera";
  73347. };
  73348. return ArcFollowCamera;
  73349. }(BABYLON.TargetCamera));
  73350. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73351. })(BABYLON || (BABYLON = {}));
  73352. //# sourceMappingURL=babylon.followCamera.js.map
  73353. var BABYLON;
  73354. (function (BABYLON) {
  73355. // We're mainly based on the logic defined into the FreeCamera code
  73356. var UniversalCamera = /** @class */ (function (_super) {
  73357. __extends(UniversalCamera, _super);
  73358. //-- end properties for backward compatibility for inputs
  73359. function UniversalCamera(name, position, scene) {
  73360. var _this = _super.call(this, name, position, scene) || this;
  73361. _this.inputs.addGamepad();
  73362. return _this;
  73363. }
  73364. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73365. //-- Begin properties for backward compatibility for inputs
  73366. get: function () {
  73367. var gamepad = this.inputs.attached["gamepad"];
  73368. if (gamepad)
  73369. return gamepad.gamepadAngularSensibility;
  73370. return 0;
  73371. },
  73372. set: function (value) {
  73373. var gamepad = this.inputs.attached["gamepad"];
  73374. if (gamepad)
  73375. gamepad.gamepadAngularSensibility = value;
  73376. },
  73377. enumerable: true,
  73378. configurable: true
  73379. });
  73380. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73381. get: function () {
  73382. var gamepad = this.inputs.attached["gamepad"];
  73383. if (gamepad)
  73384. return gamepad.gamepadMoveSensibility;
  73385. return 0;
  73386. },
  73387. set: function (value) {
  73388. var gamepad = this.inputs.attached["gamepad"];
  73389. if (gamepad)
  73390. gamepad.gamepadMoveSensibility = value;
  73391. },
  73392. enumerable: true,
  73393. configurable: true
  73394. });
  73395. UniversalCamera.prototype.getClassName = function () {
  73396. return "UniversalCamera";
  73397. };
  73398. return UniversalCamera;
  73399. }(BABYLON.TouchCamera));
  73400. BABYLON.UniversalCamera = UniversalCamera;
  73401. })(BABYLON || (BABYLON = {}));
  73402. //# sourceMappingURL=babylon.universalCamera.js.map
  73403. var BABYLON;
  73404. (function (BABYLON) {
  73405. // We're mainly based on the logic defined into the FreeCamera code
  73406. var GamepadCamera = /** @class */ (function (_super) {
  73407. __extends(GamepadCamera, _super);
  73408. //-- end properties for backward compatibility for inputs
  73409. function GamepadCamera(name, position, scene) {
  73410. return _super.call(this, name, position, scene) || this;
  73411. }
  73412. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73413. //-- Begin properties for backward compatibility for inputs
  73414. get: function () {
  73415. var gamepad = this.inputs.attached["gamepad"];
  73416. if (gamepad)
  73417. return gamepad.gamepadAngularSensibility;
  73418. return 0;
  73419. },
  73420. set: function (value) {
  73421. var gamepad = this.inputs.attached["gamepad"];
  73422. if (gamepad)
  73423. gamepad.gamepadAngularSensibility = value;
  73424. },
  73425. enumerable: true,
  73426. configurable: true
  73427. });
  73428. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73429. get: function () {
  73430. var gamepad = this.inputs.attached["gamepad"];
  73431. if (gamepad)
  73432. return gamepad.gamepadMoveSensibility;
  73433. return 0;
  73434. },
  73435. set: function (value) {
  73436. var gamepad = this.inputs.attached["gamepad"];
  73437. if (gamepad)
  73438. gamepad.gamepadMoveSensibility = value;
  73439. },
  73440. enumerable: true,
  73441. configurable: true
  73442. });
  73443. GamepadCamera.prototype.getClassName = function () {
  73444. return "GamepadCamera";
  73445. };
  73446. return GamepadCamera;
  73447. }(BABYLON.UniversalCamera));
  73448. BABYLON.GamepadCamera = GamepadCamera;
  73449. })(BABYLON || (BABYLON = {}));
  73450. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73451. var BABYLON;
  73452. (function (BABYLON) {
  73453. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73454. function PostProcessRenderPipelineManager() {
  73455. this._renderPipelines = {};
  73456. }
  73457. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73458. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73459. };
  73460. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73461. if (unique === void 0) { unique = false; }
  73462. var renderPipeline = this._renderPipelines[renderPipelineName];
  73463. if (!renderPipeline) {
  73464. return;
  73465. }
  73466. renderPipeline._attachCameras(cameras, unique);
  73467. };
  73468. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73469. var renderPipeline = this._renderPipelines[renderPipelineName];
  73470. if (!renderPipeline) {
  73471. return;
  73472. }
  73473. renderPipeline._detachCameras(cameras);
  73474. };
  73475. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73476. var renderPipeline = this._renderPipelines[renderPipelineName];
  73477. if (!renderPipeline) {
  73478. return;
  73479. }
  73480. renderPipeline._enableEffect(renderEffectName, cameras);
  73481. };
  73482. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73483. var renderPipeline = this._renderPipelines[renderPipelineName];
  73484. if (!renderPipeline) {
  73485. return;
  73486. }
  73487. renderPipeline._disableEffect(renderEffectName, cameras);
  73488. };
  73489. PostProcessRenderPipelineManager.prototype.update = function () {
  73490. for (var renderPipelineName in this._renderPipelines) {
  73491. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73492. var pipeline = this._renderPipelines[renderPipelineName];
  73493. if (!pipeline.isSupported) {
  73494. pipeline.dispose();
  73495. delete this._renderPipelines[renderPipelineName];
  73496. }
  73497. else {
  73498. pipeline._update();
  73499. }
  73500. }
  73501. }
  73502. };
  73503. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73504. for (var renderPipelineName in this._renderPipelines) {
  73505. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73506. var pipeline = this._renderPipelines[renderPipelineName];
  73507. pipeline._rebuild();
  73508. }
  73509. }
  73510. };
  73511. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73512. for (var renderPipelineName in this._renderPipelines) {
  73513. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73514. var pipeline = this._renderPipelines[renderPipelineName];
  73515. pipeline.dispose();
  73516. }
  73517. }
  73518. };
  73519. return PostProcessRenderPipelineManager;
  73520. }());
  73521. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73522. })(BABYLON || (BABYLON = {}));
  73523. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73524. var BABYLON;
  73525. (function (BABYLON) {
  73526. /**
  73527. * This represents a set of one or more post processes in Babylon.
  73528. * A post process can be used to apply a shader to a texture after it is rendered.
  73529. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73530. */
  73531. var PostProcessRenderEffect = /** @class */ (function () {
  73532. /**
  73533. * Instantiates a post process render effect.
  73534. * A post process can be used to apply a shader to a texture after it is rendered.
  73535. * @param engine The engine the effect is tied to
  73536. * @param name The name of the effect
  73537. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73538. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73539. */
  73540. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73541. this._name = name;
  73542. this._singleInstance = singleInstance || true;
  73543. this._getPostProcesses = getPostProcesses;
  73544. this._cameras = {};
  73545. this._indicesForCamera = {};
  73546. this._postProcesses = {};
  73547. }
  73548. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73549. /**
  73550. * Checks if all the post processes in the effect are supported.
  73551. */
  73552. get: function () {
  73553. for (var index in this._postProcesses) {
  73554. if (this._postProcesses.hasOwnProperty(index)) {
  73555. var pps = this._postProcesses[index];
  73556. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73557. if (!pps[ppIndex].isSupported) {
  73558. return false;
  73559. }
  73560. }
  73561. }
  73562. }
  73563. return true;
  73564. },
  73565. enumerable: true,
  73566. configurable: true
  73567. });
  73568. /**
  73569. * Updates the current state of the effect
  73570. */
  73571. PostProcessRenderEffect.prototype._update = function () {
  73572. };
  73573. /**
  73574. * Attaches the effect on cameras
  73575. * @param cameras The camera to attach to.
  73576. */
  73577. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73578. var _this = this;
  73579. var cameraKey;
  73580. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73581. if (!cams) {
  73582. return;
  73583. }
  73584. for (var i = 0; i < cams.length; i++) {
  73585. var camera = cams[i];
  73586. var cameraName = camera.name;
  73587. if (this._singleInstance) {
  73588. cameraKey = 0;
  73589. }
  73590. else {
  73591. cameraKey = cameraName;
  73592. }
  73593. if (!this._postProcesses[cameraKey]) {
  73594. var postProcess = this._getPostProcesses();
  73595. if (postProcess) {
  73596. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73597. }
  73598. }
  73599. if (!this._indicesForCamera[cameraName]) {
  73600. this._indicesForCamera[cameraName] = [];
  73601. }
  73602. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73603. var index = camera.attachPostProcess(postProcess);
  73604. _this._indicesForCamera[cameraName].push(index);
  73605. });
  73606. if (!this._cameras[cameraName]) {
  73607. this._cameras[cameraName] = camera;
  73608. }
  73609. }
  73610. };
  73611. /**
  73612. * Detatches the effect on cameras
  73613. * @param cameras The camera to detatch from.
  73614. */
  73615. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73616. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73617. if (!cams) {
  73618. return;
  73619. }
  73620. for (var i = 0; i < cams.length; i++) {
  73621. var camera = cams[i];
  73622. var cameraName = camera.name;
  73623. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73624. camera.detachPostProcess(postProcess);
  73625. });
  73626. if (this._cameras[cameraName]) {
  73627. //this._indicesForCamera.splice(index, 1);
  73628. this._cameras[cameraName] = null;
  73629. }
  73630. }
  73631. };
  73632. /**
  73633. * Enables the effect on given cameras
  73634. * @param cameras The camera to enable.
  73635. */
  73636. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73637. var _this = this;
  73638. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73639. if (!cams) {
  73640. return;
  73641. }
  73642. for (var i = 0; i < cams.length; i++) {
  73643. var camera = cams[i];
  73644. var cameraName = camera.name;
  73645. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73646. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73647. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73648. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73649. });
  73650. }
  73651. }
  73652. }
  73653. };
  73654. /**
  73655. * Disables the effect on the given cameras
  73656. * @param cameras The camera to disable.
  73657. */
  73658. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73659. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73660. if (!cams) {
  73661. return;
  73662. }
  73663. for (var i = 0; i < cams.length; i++) {
  73664. var camera = cams[i];
  73665. var cameraName = camera.name;
  73666. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73667. camera.detachPostProcess(postProcess);
  73668. });
  73669. }
  73670. };
  73671. /**
  73672. * Gets a list of the post processes contained in the effect.
  73673. * @param camera The camera to get the post processes on.
  73674. * @returns The list of the post processes in the effect.
  73675. */
  73676. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73677. if (this._singleInstance) {
  73678. return this._postProcesses[0];
  73679. }
  73680. else {
  73681. if (!camera) {
  73682. return null;
  73683. }
  73684. return this._postProcesses[camera.name];
  73685. }
  73686. };
  73687. return PostProcessRenderEffect;
  73688. }());
  73689. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73690. })(BABYLON || (BABYLON = {}));
  73691. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73692. var BABYLON;
  73693. (function (BABYLON) {
  73694. var PostProcessRenderPipeline = /** @class */ (function () {
  73695. function PostProcessRenderPipeline(engine, name) {
  73696. this.engine = engine;
  73697. this._name = name;
  73698. this._renderEffects = {};
  73699. this._renderEffectsForIsolatedPass = new Array();
  73700. this._cameras = [];
  73701. }
  73702. PostProcessRenderPipeline.prototype.getClassName = function () {
  73703. return "PostProcessRenderPipeline";
  73704. };
  73705. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73706. get: function () {
  73707. for (var renderEffectName in this._renderEffects) {
  73708. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73709. if (!this._renderEffects[renderEffectName].isSupported) {
  73710. return false;
  73711. }
  73712. }
  73713. }
  73714. return true;
  73715. },
  73716. enumerable: true,
  73717. configurable: true
  73718. });
  73719. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73720. this._renderEffects[renderEffect._name] = renderEffect;
  73721. };
  73722. // private
  73723. PostProcessRenderPipeline.prototype._rebuild = function () {
  73724. };
  73725. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73726. var renderEffects = this._renderEffects[renderEffectName];
  73727. if (!renderEffects) {
  73728. return;
  73729. }
  73730. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73731. };
  73732. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73733. var renderEffects = this._renderEffects[renderEffectName];
  73734. if (!renderEffects) {
  73735. return;
  73736. }
  73737. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73738. };
  73739. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73740. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73741. if (!cams) {
  73742. return;
  73743. }
  73744. var indicesToDelete = [];
  73745. var i;
  73746. for (i = 0; i < cams.length; i++) {
  73747. var camera = cams[i];
  73748. var cameraName = camera.name;
  73749. if (this._cameras.indexOf(camera) === -1) {
  73750. this._cameras[cameraName] = camera;
  73751. }
  73752. else if (unique) {
  73753. indicesToDelete.push(i);
  73754. }
  73755. }
  73756. for (i = 0; i < indicesToDelete.length; i++) {
  73757. cameras.splice(indicesToDelete[i], 1);
  73758. }
  73759. for (var renderEffectName in this._renderEffects) {
  73760. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73761. this._renderEffects[renderEffectName]._attachCameras(cams);
  73762. }
  73763. }
  73764. };
  73765. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73766. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73767. if (!cams) {
  73768. return;
  73769. }
  73770. for (var renderEffectName in this._renderEffects) {
  73771. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73772. this._renderEffects[renderEffectName]._detachCameras(cams);
  73773. }
  73774. }
  73775. for (var i = 0; i < cams.length; i++) {
  73776. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73777. }
  73778. };
  73779. PostProcessRenderPipeline.prototype._update = function () {
  73780. for (var renderEffectName in this._renderEffects) {
  73781. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73782. this._renderEffects[renderEffectName]._update();
  73783. }
  73784. }
  73785. for (var i = 0; i < this._cameras.length; i++) {
  73786. var cameraName = this._cameras[i].name;
  73787. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73788. this._renderEffectsForIsolatedPass[cameraName]._update();
  73789. }
  73790. }
  73791. };
  73792. PostProcessRenderPipeline.prototype._reset = function () {
  73793. this._renderEffects = {};
  73794. this._renderEffectsForIsolatedPass = new Array();
  73795. };
  73796. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73797. // 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)
  73798. var effectKeys = Object.keys(this._renderEffects);
  73799. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73800. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73801. if (postProcesses) {
  73802. postProcesses[0].samples = sampleCount;
  73803. return true;
  73804. }
  73805. }
  73806. return false;
  73807. };
  73808. PostProcessRenderPipeline.prototype.dispose = function () {
  73809. // Must be implemented by children
  73810. };
  73811. __decorate([
  73812. BABYLON.serialize()
  73813. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73814. return PostProcessRenderPipeline;
  73815. }());
  73816. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73817. })(BABYLON || (BABYLON = {}));
  73818. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73819. var BABYLON;
  73820. (function (BABYLON) {
  73821. /**
  73822. * This represents a depth renderer in Babylon.
  73823. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73824. */
  73825. var DepthRenderer = /** @class */ (function () {
  73826. /**
  73827. * Instantiates a depth renderer
  73828. * @param scene The scene the renderer belongs to
  73829. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73830. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73831. */
  73832. function DepthRenderer(scene, type, camera) {
  73833. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73834. if (camera === void 0) { camera = null; }
  73835. var _this = this;
  73836. this._scene = scene;
  73837. this._camera = camera;
  73838. var engine = scene.getEngine();
  73839. // Render target
  73840. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73841. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73842. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73843. this._depthMap.refreshRate = 1;
  73844. this._depthMap.renderParticles = false;
  73845. this._depthMap.renderList = null;
  73846. // Camera to get depth map from to support multiple concurrent cameras
  73847. this._depthMap.activeCamera = this._camera;
  73848. this._depthMap.ignoreCameraViewport = true;
  73849. this._depthMap.useCameraPostProcesses = false;
  73850. // set default depth value to 1.0 (far away)
  73851. this._depthMap.onClearObservable.add(function (engine) {
  73852. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73853. });
  73854. // Custom render function
  73855. var renderSubMesh = function (subMesh) {
  73856. var mesh = subMesh.getRenderingMesh();
  73857. var scene = _this._scene;
  73858. var engine = scene.getEngine();
  73859. var material = subMesh.getMaterial();
  73860. if (!material) {
  73861. return;
  73862. }
  73863. // Culling and reverse (right handed system)
  73864. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73865. // Managing instances
  73866. var batch = mesh._getInstancesRenderList(subMesh._id);
  73867. if (batch.mustReturn) {
  73868. return;
  73869. }
  73870. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73871. var camera = _this._camera || scene.activeCamera;
  73872. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73873. engine.enableEffect(_this._effect);
  73874. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73875. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73876. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73877. // Alpha test
  73878. if (material && material.needAlphaTesting()) {
  73879. var alphaTexture = material.getAlphaTestTexture();
  73880. if (alphaTexture) {
  73881. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73882. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73883. }
  73884. }
  73885. // Bones
  73886. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73887. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73888. }
  73889. // Draw
  73890. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73891. }
  73892. };
  73893. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73894. var index;
  73895. if (depthOnlySubMeshes.length) {
  73896. engine.setColorWrite(false);
  73897. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73898. renderSubMesh(depthOnlySubMeshes.data[index]);
  73899. }
  73900. engine.setColorWrite(true);
  73901. }
  73902. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73903. renderSubMesh(opaqueSubMeshes.data[index]);
  73904. }
  73905. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73906. renderSubMesh(alphaTestSubMeshes.data[index]);
  73907. }
  73908. };
  73909. }
  73910. /**
  73911. * Creates the depth rendering effect and checks if the effect is ready.
  73912. * @param subMesh The submesh to be used to render the depth map of
  73913. * @param useInstances If multiple world instances should be used
  73914. * @returns if the depth renderer is ready to render the depth map
  73915. */
  73916. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73917. var material = subMesh.getMaterial();
  73918. if (material.disableDepthWrite) {
  73919. return false;
  73920. }
  73921. var defines = [];
  73922. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73923. var mesh = subMesh.getMesh();
  73924. // Alpha test
  73925. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73926. defines.push("#define ALPHATEST");
  73927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73928. attribs.push(BABYLON.VertexBuffer.UVKind);
  73929. defines.push("#define UV1");
  73930. }
  73931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73932. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73933. defines.push("#define UV2");
  73934. }
  73935. }
  73936. // Bones
  73937. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73940. if (mesh.numBoneInfluencers > 4) {
  73941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73943. }
  73944. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73945. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73946. }
  73947. else {
  73948. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73949. }
  73950. // Instances
  73951. if (useInstances) {
  73952. defines.push("#define INSTANCES");
  73953. attribs.push("world0");
  73954. attribs.push("world1");
  73955. attribs.push("world2");
  73956. attribs.push("world3");
  73957. }
  73958. // Get correct effect
  73959. var join = defines.join("\n");
  73960. if (this._cachedDefines !== join) {
  73961. this._cachedDefines = join;
  73962. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73963. }
  73964. return this._effect.isReady();
  73965. };
  73966. /**
  73967. * Gets the texture which the depth map will be written to.
  73968. * @returns The depth map texture
  73969. */
  73970. DepthRenderer.prototype.getDepthMap = function () {
  73971. return this._depthMap;
  73972. };
  73973. /**
  73974. * Disposes of the depth renderer.
  73975. */
  73976. DepthRenderer.prototype.dispose = function () {
  73977. this._depthMap.dispose();
  73978. };
  73979. return DepthRenderer;
  73980. }());
  73981. BABYLON.DepthRenderer = DepthRenderer;
  73982. })(BABYLON || (BABYLON = {}));
  73983. //# sourceMappingURL=babylon.depthRenderer.js.map
  73984. var BABYLON;
  73985. (function (BABYLON) {
  73986. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73987. __extends(SSAORenderingPipeline, _super);
  73988. /**
  73989. * @constructor
  73990. * @param {string} name - The rendering pipeline name
  73991. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73992. * @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 }
  73993. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73994. */
  73995. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73996. var _this = _super.call(this, scene.getEngine(), name) || this;
  73997. // Members
  73998. /**
  73999. * The PassPostProcess id in the pipeline that contains the original scene color
  74000. */
  74001. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74002. /**
  74003. * The SSAO PostProcess id in the pipeline
  74004. */
  74005. _this.SSAORenderEffect = "SSAORenderEffect";
  74006. /**
  74007. * The horizontal blur PostProcess id in the pipeline
  74008. */
  74009. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74010. /**
  74011. * The vertical blur PostProcess id in the pipeline
  74012. */
  74013. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74014. /**
  74015. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74016. */
  74017. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74018. /**
  74019. * The output strength of the SSAO post-process. Default value is 1.0.
  74020. */
  74021. _this.totalStrength = 1.0;
  74022. /**
  74023. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  74024. */
  74025. _this.radius = 0.0001;
  74026. /**
  74027. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  74028. * Must not be equal to fallOff and superior to fallOff.
  74029. * Default value is 0.975
  74030. */
  74031. _this.area = 0.0075;
  74032. /**
  74033. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  74034. * Must not be equal to area and inferior to area.
  74035. * Default value is 0.0
  74036. */
  74037. _this.fallOff = 0.000001;
  74038. /**
  74039. * The base color of the SSAO post-process
  74040. * The final result is "base + ssao" between [0, 1]
  74041. */
  74042. _this.base = 0.5;
  74043. _this._firstUpdate = true;
  74044. _this._scene = scene;
  74045. // Set up assets
  74046. _this._createRandomTexture();
  74047. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74048. var ssaoRatio = ratio.ssaoRatio || ratio;
  74049. var combineRatio = ratio.combineRatio || ratio;
  74050. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74051. _this._createSSAOPostProcess(ssaoRatio);
  74052. _this._createBlurPostProcess(ssaoRatio);
  74053. _this._createSSAOCombinePostProcess(combineRatio);
  74054. // Set up pipeline
  74055. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74056. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74057. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74058. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74059. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74060. // Finish
  74061. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74062. if (cameras)
  74063. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74064. return _this;
  74065. }
  74066. // Public Methods
  74067. /**
  74068. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74069. */
  74070. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74071. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74072. for (var i = 0; i < this._scene.cameras.length; i++) {
  74073. var camera = this._scene.cameras[i];
  74074. this._originalColorPostProcess.dispose(camera);
  74075. this._ssaoPostProcess.dispose(camera);
  74076. this._blurHPostProcess.dispose(camera);
  74077. this._blurVPostProcess.dispose(camera);
  74078. this._ssaoCombinePostProcess.dispose(camera);
  74079. }
  74080. this._randomTexture.dispose();
  74081. if (disableDepthRender)
  74082. this._scene.disableDepthRenderer();
  74083. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74084. _super.prototype.dispose.call(this);
  74085. };
  74086. // Private Methods
  74087. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74088. var _this = this;
  74089. var size = 16;
  74090. 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);
  74091. 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);
  74092. this._blurHPostProcess.onActivateObservable.add(function () {
  74093. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74094. _this._blurHPostProcess.kernel = size * dw;
  74095. });
  74096. this._blurVPostProcess.onActivateObservable.add(function () {
  74097. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74098. _this._blurVPostProcess.kernel = size * dw;
  74099. });
  74100. };
  74101. SSAORenderingPipeline.prototype._rebuild = function () {
  74102. this._firstUpdate = true;
  74103. _super.prototype._rebuild.call(this);
  74104. };
  74105. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74106. var _this = this;
  74107. var numSamples = 16;
  74108. var sampleSphere = [
  74109. 0.5381, 0.1856, -0.4319,
  74110. 0.1379, 0.2486, 0.4430,
  74111. 0.3371, 0.5679, -0.0057,
  74112. -0.6999, -0.0451, -0.0019,
  74113. 0.0689, -0.1598, -0.8547,
  74114. 0.0560, 0.0069, -0.1843,
  74115. -0.0146, 0.1402, 0.0762,
  74116. 0.0100, -0.1924, -0.0344,
  74117. -0.3577, -0.5301, -0.4358,
  74118. -0.3169, 0.1063, 0.0158,
  74119. 0.0103, -0.5869, 0.0046,
  74120. -0.0897, -0.4940, 0.3287,
  74121. 0.7119, -0.0154, -0.0918,
  74122. -0.0533, 0.0596, -0.5411,
  74123. 0.0352, -0.0631, 0.5460,
  74124. -0.4776, 0.2847, -0.0271
  74125. ];
  74126. var samplesFactor = 1.0 / numSamples;
  74127. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74128. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74129. "area", "fallOff", "base", "range", "viewport"
  74130. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74131. this._ssaoPostProcess.onApply = function (effect) {
  74132. if (_this._firstUpdate) {
  74133. effect.setArray3("sampleSphere", sampleSphere);
  74134. effect.setFloat("samplesFactor", samplesFactor);
  74135. effect.setFloat("randTextureTiles", 4.0);
  74136. }
  74137. effect.setFloat("totalStrength", _this.totalStrength);
  74138. effect.setFloat("radius", _this.radius);
  74139. effect.setFloat("area", _this.area);
  74140. effect.setFloat("fallOff", _this.fallOff);
  74141. effect.setFloat("base", _this.base);
  74142. effect.setTexture("textureSampler", _this._depthTexture);
  74143. effect.setTexture("randomSampler", _this._randomTexture);
  74144. };
  74145. };
  74146. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74147. var _this = this;
  74148. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74149. this._ssaoCombinePostProcess.onApply = function (effect) {
  74150. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74151. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74152. };
  74153. };
  74154. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74155. var size = 512;
  74156. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74157. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74158. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74159. var context = this._randomTexture.getContext();
  74160. var rand = function (min, max) {
  74161. return Math.random() * (max - min) + min;
  74162. };
  74163. var randVector = BABYLON.Vector3.Zero();
  74164. for (var x = 0; x < size; x++) {
  74165. for (var y = 0; y < size; y++) {
  74166. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74167. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74168. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74169. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74170. context.fillRect(x, y, 1, 1);
  74171. }
  74172. }
  74173. this._randomTexture.update(false);
  74174. };
  74175. __decorate([
  74176. BABYLON.serialize()
  74177. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74178. __decorate([
  74179. BABYLON.serialize()
  74180. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74181. __decorate([
  74182. BABYLON.serialize()
  74183. ], SSAORenderingPipeline.prototype, "area", void 0);
  74184. __decorate([
  74185. BABYLON.serialize()
  74186. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74187. __decorate([
  74188. BABYLON.serialize()
  74189. ], SSAORenderingPipeline.prototype, "base", void 0);
  74190. return SSAORenderingPipeline;
  74191. }(BABYLON.PostProcessRenderPipeline));
  74192. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74193. })(BABYLON || (BABYLON = {}));
  74194. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74195. var BABYLON;
  74196. (function (BABYLON) {
  74197. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74198. __extends(SSAO2RenderingPipeline, _super);
  74199. /**
  74200. * @constructor
  74201. * @param {string} name - The rendering pipeline name
  74202. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74203. * @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 }
  74204. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74205. */
  74206. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74207. var _this = _super.call(this, scene.getEngine(), name) || this;
  74208. // Members
  74209. /**
  74210. * The PassPostProcess id in the pipeline that contains the original scene color
  74211. */
  74212. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74213. /**
  74214. * The SSAO PostProcess id in the pipeline
  74215. */
  74216. _this.SSAORenderEffect = "SSAORenderEffect";
  74217. /**
  74218. * The horizontal blur PostProcess id in the pipeline
  74219. */
  74220. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74221. /**
  74222. * The vertical blur PostProcess id in the pipeline
  74223. */
  74224. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74225. /**
  74226. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74227. */
  74228. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74229. /**
  74230. * The output strength of the SSAO post-process. Default value is 1.0.
  74231. */
  74232. _this.totalStrength = 1.0;
  74233. /**
  74234. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74235. */
  74236. _this.maxZ = 100.0;
  74237. /**
  74238. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74239. */
  74240. _this.minZAspect = 0.2;
  74241. /**
  74242. * Number of samples used for the SSAO calculations. Default value is 8
  74243. */
  74244. _this._samples = 8;
  74245. /**
  74246. * Are we using bilateral blur ?
  74247. */
  74248. _this._expensiveBlur = true;
  74249. /**
  74250. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74251. */
  74252. _this.radius = 2.0;
  74253. /**
  74254. * The base color of the SSAO post-process
  74255. * The final result is "base + ssao" between [0, 1]
  74256. */
  74257. _this.base = 0.1;
  74258. _this._firstUpdate = true;
  74259. _this._scene = scene;
  74260. _this._ratio = ratio;
  74261. if (!_this.isSupported) {
  74262. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74263. return _this;
  74264. }
  74265. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74266. var blurRatio = _this._ratio.blurRatio || ratio;
  74267. // Set up assets
  74268. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74269. _this._createRandomTexture();
  74270. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74271. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74272. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74273. _this._createSSAOPostProcess(1.0);
  74274. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74275. _this._createSSAOCombinePostProcess(blurRatio);
  74276. // Set up pipeline
  74277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74278. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74282. // Finish
  74283. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74284. if (cameras)
  74285. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74286. return _this;
  74287. }
  74288. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74289. get: function () {
  74290. return this._samples;
  74291. },
  74292. set: function (n) {
  74293. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74294. this._samples = n;
  74295. this._sampleSphere = this._generateHemisphere();
  74296. this._firstUpdate = true;
  74297. },
  74298. enumerable: true,
  74299. configurable: true
  74300. });
  74301. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74302. get: function () {
  74303. return this._expensiveBlur;
  74304. },
  74305. set: function (b) {
  74306. 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"]);
  74307. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74308. this._expensiveBlur = b;
  74309. this._firstUpdate = true;
  74310. },
  74311. enumerable: true,
  74312. configurable: true
  74313. });
  74314. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74315. /**
  74316. * Support test.
  74317. */
  74318. get: function () {
  74319. var engine = BABYLON.Engine.LastCreatedEngine;
  74320. if (!engine) {
  74321. return false;
  74322. }
  74323. return engine.getCaps().drawBuffersExtension;
  74324. },
  74325. enumerable: true,
  74326. configurable: true
  74327. });
  74328. // Public Methods
  74329. /**
  74330. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74331. */
  74332. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74333. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74334. for (var i = 0; i < this._scene.cameras.length; i++) {
  74335. var camera = this._scene.cameras[i];
  74336. this._originalColorPostProcess.dispose(camera);
  74337. this._ssaoPostProcess.dispose(camera);
  74338. this._blurHPostProcess.dispose(camera);
  74339. this._blurVPostProcess.dispose(camera);
  74340. this._ssaoCombinePostProcess.dispose(camera);
  74341. }
  74342. this._randomTexture.dispose();
  74343. if (disableGeometryBufferRenderer)
  74344. this._scene.disableGeometryBufferRenderer();
  74345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74346. _super.prototype.dispose.call(this);
  74347. };
  74348. // Private Methods
  74349. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74350. var _this = this;
  74351. this._samplerOffsets = [];
  74352. var expensive = this.expensiveBlur;
  74353. for (var i = -8; i < 8; i++) {
  74354. this._samplerOffsets.push(i * 2 + 0.5);
  74355. }
  74356. 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");
  74357. this._blurHPostProcess.onApply = function (effect) {
  74358. if (!_this._scene.activeCamera) {
  74359. return;
  74360. }
  74361. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74362. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74363. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74364. effect.setFloat("radius", _this.radius);
  74365. effect.setTexture("depthSampler", _this._depthTexture);
  74366. if (_this._firstUpdate) {
  74367. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74368. }
  74369. };
  74370. 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");
  74371. this._blurVPostProcess.onApply = function (effect) {
  74372. if (!_this._scene.activeCamera) {
  74373. return;
  74374. }
  74375. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74376. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74377. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74378. effect.setFloat("radius", _this.radius);
  74379. effect.setTexture("depthSampler", _this._depthTexture);
  74380. if (_this._firstUpdate) {
  74381. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74382. _this._firstUpdate = false;
  74383. }
  74384. };
  74385. };
  74386. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74387. this._firstUpdate = true;
  74388. _super.prototype._rebuild.call(this);
  74389. };
  74390. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74391. var numSamples = this.samples;
  74392. var result = [];
  74393. var vector, scale;
  74394. var rand = function (min, max) {
  74395. return Math.random() * (max - min) + min;
  74396. };
  74397. var i = 0;
  74398. while (i < numSamples) {
  74399. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74400. vector.normalize();
  74401. scale = i / numSamples;
  74402. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74403. vector.scaleInPlace(scale);
  74404. result.push(vector.x, vector.y, vector.z);
  74405. i++;
  74406. }
  74407. return result;
  74408. };
  74409. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74410. var _this = this;
  74411. var numSamples = this.samples;
  74412. this._sampleSphere = this._generateHemisphere();
  74413. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74414. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74415. "base", "range", "projection", "near", "far", "texelSize",
  74416. "xViewport", "yViewport", "maxZ", "minZAspect"
  74417. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74418. this._ssaoPostProcess.onApply = function (effect) {
  74419. if (_this._firstUpdate) {
  74420. effect.setArray3("sampleSphere", _this._sampleSphere);
  74421. effect.setFloat("randTextureTiles", 4.0);
  74422. }
  74423. if (!_this._scene.activeCamera) {
  74424. return;
  74425. }
  74426. effect.setFloat("samplesFactor", 1 / _this.samples);
  74427. effect.setFloat("totalStrength", _this.totalStrength);
  74428. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74429. effect.setFloat("radius", _this.radius);
  74430. effect.setFloat("maxZ", _this.maxZ);
  74431. effect.setFloat("minZAspect", _this.minZAspect);
  74432. effect.setFloat("base", _this.base);
  74433. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74434. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74435. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74436. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74437. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74438. effect.setTexture("textureSampler", _this._depthTexture);
  74439. effect.setTexture("normalSampler", _this._normalTexture);
  74440. effect.setTexture("randomSampler", _this._randomTexture);
  74441. };
  74442. };
  74443. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74444. var _this = this;
  74445. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74446. this._ssaoCombinePostProcess.onApply = function (effect) {
  74447. var viewport = _this._scene.activeCamera.viewport;
  74448. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74449. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74450. };
  74451. };
  74452. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74453. var size = 512;
  74454. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74455. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74456. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74457. var context = this._randomTexture.getContext();
  74458. var rand = function (min, max) {
  74459. return Math.random() * (max - min) + min;
  74460. };
  74461. var randVector = BABYLON.Vector3.Zero();
  74462. for (var x = 0; x < size; x++) {
  74463. for (var y = 0; y < size; y++) {
  74464. randVector.x = rand(0.0, 1.0);
  74465. randVector.y = rand(0.0, 1.0);
  74466. randVector.z = 0.0;
  74467. randVector.normalize();
  74468. randVector.scaleInPlace(255);
  74469. randVector.x = Math.floor(randVector.x);
  74470. randVector.y = Math.floor(randVector.y);
  74471. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74472. context.fillRect(x, y, 1, 1);
  74473. }
  74474. }
  74475. this._randomTexture.update(false);
  74476. };
  74477. /**
  74478. * Serialize the rendering pipeline (Used when exporting)
  74479. * @returns the serialized object
  74480. */
  74481. SSAO2RenderingPipeline.prototype.serialize = function () {
  74482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74483. serializationObject.customType = "SSAO2RenderingPipeline";
  74484. return serializationObject;
  74485. };
  74486. /**
  74487. * Parse the serialized pipeline
  74488. * @param source Source pipeline.
  74489. * @param scene The scene to load the pipeline to.
  74490. * @param rootUrl The URL of the serialized pipeline.
  74491. * @returns An instantiated pipeline from the serialized object.
  74492. */
  74493. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74494. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74495. };
  74496. __decorate([
  74497. BABYLON.serialize()
  74498. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74499. __decorate([
  74500. BABYLON.serialize()
  74501. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74502. __decorate([
  74503. BABYLON.serialize()
  74504. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74505. __decorate([
  74506. BABYLON.serialize("samples")
  74507. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74508. __decorate([
  74509. BABYLON.serialize()
  74510. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74511. __decorate([
  74512. BABYLON.serialize("expensiveBlur")
  74513. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74514. __decorate([
  74515. BABYLON.serialize()
  74516. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74517. __decorate([
  74518. BABYLON.serialize()
  74519. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74520. return SSAO2RenderingPipeline;
  74521. }(BABYLON.PostProcessRenderPipeline));
  74522. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74523. })(BABYLON || (BABYLON = {}));
  74524. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74525. // BABYLON.JS Chromatic Aberration GLSL Shader
  74526. // Author: Olivier Guyot
  74527. // Separates very slightly R, G and B colors on the edges of the screen
  74528. // Inspired by Francois Tarlier & Martins Upitis
  74529. var BABYLON;
  74530. (function (BABYLON) {
  74531. var LensRenderingPipeline = /** @class */ (function (_super) {
  74532. __extends(LensRenderingPipeline, _super);
  74533. /**
  74534. * @constructor
  74535. *
  74536. * Effect parameters are as follow:
  74537. * {
  74538. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74539. * edge_blur: number; // from 0 to x (1 for realism)
  74540. * distortion: number; // from 0 to x (1 for realism)
  74541. * grain_amount: number; // from 0 to 1
  74542. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74543. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74544. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74545. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74546. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74547. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74548. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74549. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74550. * }
  74551. * Note: if an effect parameter is unset, effect is disabled
  74552. *
  74553. * @param {string} name - The rendering pipeline name
  74554. * @param {object} parameters - An object containing all parameters (see above)
  74555. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74556. * @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)
  74557. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74558. */
  74559. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74560. if (ratio === void 0) { ratio = 1.0; }
  74561. var _this = _super.call(this, scene.getEngine(), name) || this;
  74562. // Lens effects can be of the following:
  74563. // - chromatic aberration (slight shift of RGB colors)
  74564. // - blur on the edge of the lens
  74565. // - lens distortion
  74566. // - depth-of-field blur & highlights enhancing
  74567. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74568. // - grain effect (noise or custom texture)
  74569. // Two additional texture samplers are needed:
  74570. // - depth map (for depth-of-field)
  74571. // - grain texture
  74572. /**
  74573. * The chromatic aberration PostProcess id in the pipeline
  74574. */
  74575. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74576. /**
  74577. * The highlights enhancing PostProcess id in the pipeline
  74578. */
  74579. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74580. /**
  74581. * The depth-of-field PostProcess id in the pipeline
  74582. */
  74583. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74584. _this._scene = scene;
  74585. // Fetch texture samplers
  74586. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74587. if (parameters.grain_texture) {
  74588. _this._grainTexture = parameters.grain_texture;
  74589. }
  74590. else {
  74591. _this._createGrainTexture();
  74592. }
  74593. // save parameters
  74594. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74595. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74596. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74597. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74598. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74599. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74600. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74601. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74602. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74603. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74604. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74605. // Create effects
  74606. _this._createChromaticAberrationPostProcess(ratio);
  74607. _this._createHighlightsPostProcess(ratio);
  74608. _this._createDepthOfFieldPostProcess(ratio / 4);
  74609. // Set up pipeline
  74610. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74612. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74613. if (_this._highlightsGain === -1) {
  74614. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74615. }
  74616. // Finish
  74617. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74618. if (cameras) {
  74619. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74620. }
  74621. return _this;
  74622. }
  74623. // public methods (self explanatory)
  74624. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74625. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74626. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74627. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74628. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74629. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74630. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74631. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74632. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74633. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74634. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74635. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74636. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74637. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74638. };
  74639. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74640. this._highlightsPostProcess.updateEffect();
  74641. };
  74642. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74643. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74644. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74645. this._highlightsGain = amount;
  74646. };
  74647. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74648. if (this._highlightsGain === -1) {
  74649. this._highlightsGain = 1.0;
  74650. }
  74651. this._highlightsThreshold = amount;
  74652. };
  74653. LensRenderingPipeline.prototype.disableHighlights = function () {
  74654. this._highlightsGain = -1;
  74655. };
  74656. /**
  74657. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74658. */
  74659. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74660. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74661. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74662. this._chromaticAberrationPostProcess = null;
  74663. this._highlightsPostProcess = null;
  74664. this._depthOfFieldPostProcess = null;
  74665. this._grainTexture.dispose();
  74666. if (disableDepthRender)
  74667. this._scene.disableDepthRenderer();
  74668. };
  74669. // colors shifting and distortion
  74670. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74671. var _this = this;
  74672. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74673. [], // samplers
  74674. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74675. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74676. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74677. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74678. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74679. effect.setFloat('radialIntensity', 1);
  74680. effect.setFloat2('direction', 17, 17);
  74681. effect.setFloat2('centerPosition', 0.5, 0.5);
  74682. };
  74683. };
  74684. // highlights enhancing
  74685. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74686. var _this = this;
  74687. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74688. [], // samplers
  74689. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74690. this._highlightsPostProcess.onApply = function (effect) {
  74691. effect.setFloat('gain', _this._highlightsGain);
  74692. effect.setFloat('threshold', _this._highlightsThreshold);
  74693. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74694. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74695. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74696. };
  74697. };
  74698. // colors shifting and distortion
  74699. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74700. var _this = this;
  74701. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74702. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74703. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74704. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74705. this._depthOfFieldPostProcess.onApply = function (effect) {
  74706. effect.setTexture("depthSampler", _this._depthTexture);
  74707. effect.setTexture("grainSampler", _this._grainTexture);
  74708. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74709. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74710. effect.setFloat('grain_amount', _this._grainAmount);
  74711. effect.setBool('blur_noise', _this._blurNoise);
  74712. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74713. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74714. effect.setFloat('distortion', _this._distortion);
  74715. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74716. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74717. effect.setFloat('aperture', _this._dofAperture);
  74718. effect.setFloat('darken', _this._dofDarken);
  74719. effect.setFloat('edge_blur', _this._edgeBlur);
  74720. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74721. if (_this._scene.activeCamera) {
  74722. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74723. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74724. }
  74725. };
  74726. };
  74727. // creates a black and white random noise texture, 512x512
  74728. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74729. var size = 512;
  74730. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74731. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74732. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74733. var context = this._grainTexture.getContext();
  74734. var rand = function (min, max) {
  74735. return Math.random() * (max - min) + min;
  74736. };
  74737. var value;
  74738. for (var x = 0; x < size; x++) {
  74739. for (var y = 0; y < size; y++) {
  74740. value = Math.floor(rand(0.42, 0.58) * 255);
  74741. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74742. context.fillRect(x, y, 1, 1);
  74743. }
  74744. }
  74745. this._grainTexture.update(false);
  74746. };
  74747. return LensRenderingPipeline;
  74748. }(BABYLON.PostProcessRenderPipeline));
  74749. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74750. })(BABYLON || (BABYLON = {}));
  74751. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74752. var BABYLON;
  74753. (function (BABYLON) {
  74754. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74755. __extends(StandardRenderingPipeline, _super);
  74756. /**
  74757. * @constructor
  74758. * @param {string} name - The rendering pipeline name
  74759. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74760. * @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)
  74761. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74762. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74763. */
  74764. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74765. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74766. var _this = _super.call(this, scene.getEngine(), name) || this;
  74767. _this.downSampleX4PostProcess = null;
  74768. _this.brightPassPostProcess = null;
  74769. _this.blurHPostProcesses = [];
  74770. _this.blurVPostProcesses = [];
  74771. _this.textureAdderPostProcess = null;
  74772. _this.volumetricLightPostProcess = null;
  74773. _this.volumetricLightSmoothXPostProcess = null;
  74774. _this.volumetricLightSmoothYPostProcess = null;
  74775. _this.volumetricLightMergePostProces = null;
  74776. _this.volumetricLightFinalPostProcess = null;
  74777. _this.luminancePostProcess = null;
  74778. _this.luminanceDownSamplePostProcesses = [];
  74779. _this.hdrPostProcess = null;
  74780. _this.textureAdderFinalPostProcess = null;
  74781. _this.lensFlareFinalPostProcess = null;
  74782. _this.hdrFinalPostProcess = null;
  74783. _this.lensFlarePostProcess = null;
  74784. _this.lensFlareComposePostProcess = null;
  74785. _this.motionBlurPostProcess = null;
  74786. _this.depthOfFieldPostProcess = null;
  74787. // Values
  74788. _this.brightThreshold = 1.0;
  74789. _this.blurWidth = 512.0;
  74790. _this.horizontalBlur = false;
  74791. _this.exposure = 1.0;
  74792. _this.lensTexture = null;
  74793. _this.volumetricLightCoefficient = 0.2;
  74794. _this.volumetricLightPower = 4.0;
  74795. _this.volumetricLightBlurScale = 64.0;
  74796. _this.sourceLight = null;
  74797. _this.hdrMinimumLuminance = 1.0;
  74798. _this.hdrDecreaseRate = 0.5;
  74799. _this.hdrIncreaseRate = 0.5;
  74800. _this.lensColorTexture = null;
  74801. _this.lensFlareStrength = 20.0;
  74802. _this.lensFlareGhostDispersal = 1.4;
  74803. _this.lensFlareHaloWidth = 0.7;
  74804. _this.lensFlareDistortionStrength = 16.0;
  74805. _this.lensStarTexture = null;
  74806. _this.lensFlareDirtTexture = null;
  74807. _this.depthOfFieldDistance = 10.0;
  74808. _this.depthOfFieldBlurWidth = 64.0;
  74809. _this.motionStrength = 1.0;
  74810. // IAnimatable
  74811. _this.animations = [];
  74812. _this._currentDepthOfFieldSource = null;
  74813. _this._hdrCurrentLuminance = 1.0;
  74814. // Getters and setters
  74815. _this._bloomEnabled = true;
  74816. _this._depthOfFieldEnabled = false;
  74817. _this._vlsEnabled = false;
  74818. _this._lensFlareEnabled = false;
  74819. _this._hdrEnabled = false;
  74820. _this._motionBlurEnabled = false;
  74821. _this._motionBlurSamples = 64.0;
  74822. _this._volumetricLightStepsCount = 50.0;
  74823. _this._cameras = cameras || [];
  74824. // Initialize
  74825. _this._scene = scene;
  74826. _this._basePostProcess = originalPostProcess;
  74827. _this._ratio = ratio;
  74828. // Misc
  74829. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74830. // Finish
  74831. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74832. _this._buildPipeline();
  74833. return _this;
  74834. }
  74835. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74836. get: function () {
  74837. return this._bloomEnabled;
  74838. },
  74839. set: function (enabled) {
  74840. if (this._bloomEnabled === enabled) {
  74841. return;
  74842. }
  74843. this._bloomEnabled = enabled;
  74844. this._buildPipeline();
  74845. },
  74846. enumerable: true,
  74847. configurable: true
  74848. });
  74849. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74850. get: function () {
  74851. return this._depthOfFieldEnabled;
  74852. },
  74853. set: function (enabled) {
  74854. if (this._depthOfFieldEnabled === enabled) {
  74855. return;
  74856. }
  74857. this._depthOfFieldEnabled = enabled;
  74858. this._buildPipeline();
  74859. },
  74860. enumerable: true,
  74861. configurable: true
  74862. });
  74863. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74864. get: function () {
  74865. return this._lensFlareEnabled;
  74866. },
  74867. set: function (enabled) {
  74868. if (this._lensFlareEnabled === enabled) {
  74869. return;
  74870. }
  74871. this._lensFlareEnabled = enabled;
  74872. this._buildPipeline();
  74873. },
  74874. enumerable: true,
  74875. configurable: true
  74876. });
  74877. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74878. get: function () {
  74879. return this._hdrEnabled;
  74880. },
  74881. set: function (enabled) {
  74882. if (this._hdrEnabled === enabled) {
  74883. return;
  74884. }
  74885. this._hdrEnabled = enabled;
  74886. this._buildPipeline();
  74887. },
  74888. enumerable: true,
  74889. configurable: true
  74890. });
  74891. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74892. get: function () {
  74893. return this._vlsEnabled;
  74894. },
  74895. set: function (enabled) {
  74896. if (this._vlsEnabled === enabled) {
  74897. return;
  74898. }
  74899. if (enabled) {
  74900. var geometry = this._scene.enableGeometryBufferRenderer();
  74901. if (!geometry) {
  74902. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74903. return;
  74904. }
  74905. }
  74906. this._vlsEnabled = enabled;
  74907. this._buildPipeline();
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74913. get: function () {
  74914. return this._motionBlurEnabled;
  74915. },
  74916. set: function (enabled) {
  74917. if (this._motionBlurEnabled === enabled) {
  74918. return;
  74919. }
  74920. this._motionBlurEnabled = enabled;
  74921. this._buildPipeline();
  74922. },
  74923. enumerable: true,
  74924. configurable: true
  74925. });
  74926. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74927. get: function () {
  74928. return this._volumetricLightStepsCount;
  74929. },
  74930. set: function (count) {
  74931. if (this.volumetricLightPostProcess) {
  74932. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74933. }
  74934. this._volumetricLightStepsCount = count;
  74935. },
  74936. enumerable: true,
  74937. configurable: true
  74938. });
  74939. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74940. get: function () {
  74941. return this._motionBlurSamples;
  74942. },
  74943. set: function (samples) {
  74944. if (this.motionBlurPostProcess) {
  74945. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74946. }
  74947. this._motionBlurSamples = samples;
  74948. },
  74949. enumerable: true,
  74950. configurable: true
  74951. });
  74952. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74953. var _this = this;
  74954. var ratio = this._ratio;
  74955. var scene = this._scene;
  74956. this._disposePostProcesses();
  74957. this._reset();
  74958. // Create pass post-process
  74959. if (!this._basePostProcess) {
  74960. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74961. this.originalPostProcess.onApply = function (effect) {
  74962. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74963. };
  74964. }
  74965. else {
  74966. this.originalPostProcess = this._basePostProcess;
  74967. }
  74968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74969. this._currentDepthOfFieldSource = this.originalPostProcess;
  74970. if (this._bloomEnabled) {
  74971. // Create down sample X4 post-process
  74972. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74973. // Create bright pass post-process
  74974. this._createBrightPassPostProcess(scene, ratio / 2);
  74975. // Create gaussian blur post-processes (down sampling blurs)
  74976. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74977. // Create texture adder post-process
  74978. this._createTextureAdderPostProcess(scene, ratio);
  74979. // Create depth-of-field source post-process
  74980. 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);
  74981. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74982. }
  74983. if (this._vlsEnabled) {
  74984. // Create volumetric light
  74985. this._createVolumetricLightPostProcess(scene, ratio);
  74986. // Create volumetric light final post-process
  74987. 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);
  74988. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74989. }
  74990. if (this._lensFlareEnabled) {
  74991. // Create lens flare post-process
  74992. this._createLensFlarePostProcess(scene, ratio);
  74993. // Create depth-of-field source post-process post lens-flare and disable it now
  74994. 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);
  74995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74996. }
  74997. if (this._hdrEnabled) {
  74998. // Create luminance
  74999. this._createLuminancePostProcesses(scene, this._floatTextureType);
  75000. // Create HDR
  75001. this._createHdrPostProcess(scene, ratio);
  75002. // Create depth-of-field source post-process post hdr and disable it now
  75003. 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);
  75004. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  75005. }
  75006. if (this._depthOfFieldEnabled) {
  75007. // Create gaussian blur used by depth-of-field
  75008. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  75009. // Create depth-of-field post-process
  75010. this._createDepthOfFieldPostProcess(scene, ratio);
  75011. }
  75012. if (this._motionBlurEnabled) {
  75013. // Create motion blur post-process
  75014. this._createMotionBlurPostProcess(scene, ratio);
  75015. }
  75016. if (this._cameras !== null) {
  75017. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75018. }
  75019. };
  75020. // Down Sample X4 Post-Processs
  75021. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  75022. var _this = this;
  75023. var downSampleX4Offsets = new Array(32);
  75024. 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);
  75025. this.downSampleX4PostProcess.onApply = function (effect) {
  75026. var id = 0;
  75027. var width = _this.downSampleX4PostProcess.width;
  75028. var height = _this.downSampleX4PostProcess.height;
  75029. for (var i = -2; i < 2; i++) {
  75030. for (var j = -2; j < 2; j++) {
  75031. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  75032. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  75033. id += 2;
  75034. }
  75035. }
  75036. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75037. };
  75038. // Add to pipeline
  75039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75040. };
  75041. // Brightpass Post-Process
  75042. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75043. var _this = this;
  75044. var brightOffsets = new Array(8);
  75045. 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);
  75046. this.brightPassPostProcess.onApply = function (effect) {
  75047. var sU = (1.0 / _this.brightPassPostProcess.width);
  75048. var sV = (1.0 / _this.brightPassPostProcess.height);
  75049. brightOffsets[0] = -0.5 * sU;
  75050. brightOffsets[1] = 0.5 * sV;
  75051. brightOffsets[2] = 0.5 * sU;
  75052. brightOffsets[3] = 0.5 * sV;
  75053. brightOffsets[4] = -0.5 * sU;
  75054. brightOffsets[5] = -0.5 * sV;
  75055. brightOffsets[6] = 0.5 * sU;
  75056. brightOffsets[7] = -0.5 * sV;
  75057. effect.setArray2("dsOffsets", brightOffsets);
  75058. effect.setFloat("brightThreshold", _this.brightThreshold);
  75059. };
  75060. // Add to pipeline
  75061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75062. };
  75063. // Create blur H&V post-processes
  75064. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75065. var _this = this;
  75066. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75067. var engine = scene.getEngine();
  75068. 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);
  75069. 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);
  75070. blurX.onActivateObservable.add(function () {
  75071. var dw = blurX.width / engine.getRenderWidth();
  75072. blurX.kernel = _this[blurWidthKey] * dw;
  75073. });
  75074. blurY.onActivateObservable.add(function () {
  75075. var dw = blurY.height / engine.getRenderHeight();
  75076. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75077. });
  75078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75080. this.blurHPostProcesses.push(blurX);
  75081. this.blurVPostProcesses.push(blurY);
  75082. };
  75083. // Create texture adder post-process
  75084. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75085. var _this = this;
  75086. 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);
  75087. this.textureAdderPostProcess.onApply = function (effect) {
  75088. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75089. effect.setTexture("lensSampler", _this.lensTexture);
  75090. effect.setFloat("exposure", _this.exposure);
  75091. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75092. };
  75093. // Add to pipeline
  75094. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75095. };
  75096. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75097. var _this = this;
  75098. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75099. geometryRenderer.enablePosition = true;
  75100. var geometry = geometryRenderer.getGBuffer();
  75101. // Base post-process
  75102. 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));
  75103. var depthValues = BABYLON.Vector2.Zero();
  75104. this.volumetricLightPostProcess.onApply = function (effect) {
  75105. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75106. var generator = _this.sourceLight.getShadowGenerator();
  75107. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75108. effect.setTexture("positionSampler", geometry.textures[2]);
  75109. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75110. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75111. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75112. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75113. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75114. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75115. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75116. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75117. effect.setVector2("depthValues", depthValues);
  75118. }
  75119. };
  75120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75121. // Smooth
  75122. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75123. // Merge
  75124. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75125. this.volumetricLightMergePostProces.onApply = function (effect) {
  75126. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75127. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75128. };
  75129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75130. };
  75131. // Create luminance
  75132. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75133. var _this = this;
  75134. // Create luminance
  75135. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75136. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75137. var offsets = [];
  75138. this.luminancePostProcess.onApply = function (effect) {
  75139. var sU = (1.0 / _this.luminancePostProcess.width);
  75140. var sV = (1.0 / _this.luminancePostProcess.height);
  75141. offsets[0] = -0.5 * sU;
  75142. offsets[1] = 0.5 * sV;
  75143. offsets[2] = 0.5 * sU;
  75144. offsets[3] = 0.5 * sV;
  75145. offsets[4] = -0.5 * sU;
  75146. offsets[5] = -0.5 * sV;
  75147. offsets[6] = 0.5 * sU;
  75148. offsets[7] = -0.5 * sV;
  75149. effect.setArray2("lumOffsets", offsets);
  75150. };
  75151. // Add to pipeline
  75152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75153. // Create down sample luminance
  75154. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75155. var size = Math.pow(3, i);
  75156. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75157. if (i === 0) {
  75158. defines += "#define FINAL_DOWN_SAMPLER";
  75159. }
  75160. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75161. this.luminanceDownSamplePostProcesses.push(postProcess);
  75162. }
  75163. // Create callbacks and add effects
  75164. var lastLuminance = this.luminancePostProcess;
  75165. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75166. var downSampleOffsets = new Array(18);
  75167. pp.onApply = function (effect) {
  75168. if (!lastLuminance) {
  75169. return;
  75170. }
  75171. var id = 0;
  75172. for (var x = -1; x < 2; x++) {
  75173. for (var y = -1; y < 2; y++) {
  75174. downSampleOffsets[id] = x / lastLuminance.width;
  75175. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75176. id += 2;
  75177. }
  75178. }
  75179. effect.setArray2("dsOffsets", downSampleOffsets);
  75180. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75181. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75182. lastLuminance = _this.luminancePostProcess;
  75183. }
  75184. else {
  75185. lastLuminance = pp;
  75186. }
  75187. };
  75188. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75189. pp.onAfterRender = function (effect) {
  75190. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75191. 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);
  75192. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75193. };
  75194. }
  75195. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75196. });
  75197. };
  75198. // Create HDR post-process
  75199. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75200. var _this = this;
  75201. 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);
  75202. var outputLiminance = 1;
  75203. var time = 0;
  75204. var lastTime = 0;
  75205. this.hdrPostProcess.onApply = function (effect) {
  75206. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75207. time += scene.getEngine().getDeltaTime();
  75208. if (outputLiminance < 0) {
  75209. outputLiminance = _this._hdrCurrentLuminance;
  75210. }
  75211. else {
  75212. var dt = (lastTime - time) / 1000.0;
  75213. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75214. outputLiminance += _this.hdrDecreaseRate * dt;
  75215. }
  75216. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75217. outputLiminance -= _this.hdrIncreaseRate * dt;
  75218. }
  75219. else {
  75220. outputLiminance = _this._hdrCurrentLuminance;
  75221. }
  75222. }
  75223. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75224. effect.setFloat("averageLuminance", outputLiminance);
  75225. lastTime = time;
  75226. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75227. };
  75228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75229. };
  75230. // Create lens flare post-process
  75231. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75232. var _this = this;
  75233. 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);
  75234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75235. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75236. 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);
  75237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75238. var resolution = new BABYLON.Vector2(0, 0);
  75239. // Lens flare
  75240. this.lensFlarePostProcess.onApply = function (effect) {
  75241. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75242. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75243. effect.setFloat("strength", _this.lensFlareStrength);
  75244. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75245. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75246. // Shift
  75247. resolution.x = _this.lensFlarePostProcess.width;
  75248. resolution.y = _this.lensFlarePostProcess.height;
  75249. effect.setVector2("resolution", resolution);
  75250. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75251. };
  75252. // Compose
  75253. 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);
  75254. 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);
  75255. this.lensFlareComposePostProcess.onApply = function (effect) {
  75256. if (!_this._scene.activeCamera) {
  75257. return;
  75258. }
  75259. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75260. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75261. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75262. // Lens start rotation matrix
  75263. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75264. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75265. 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));
  75266. camRot *= 4.0;
  75267. 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);
  75268. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75269. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75270. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75271. };
  75272. };
  75273. // Create depth-of-field post-process
  75274. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75275. var _this = this;
  75276. 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);
  75277. this.depthOfFieldPostProcess.onApply = function (effect) {
  75278. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75279. effect.setTexture("depthSampler", _this._getDepthTexture());
  75280. effect.setFloat("distance", _this.depthOfFieldDistance);
  75281. };
  75282. // Add to pipeline
  75283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75284. };
  75285. // Create motion blur post-process
  75286. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75287. var _this = this;
  75288. 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);
  75289. var motionScale = 0;
  75290. var prevViewProjection = BABYLON.Matrix.Identity();
  75291. var invViewProjection = BABYLON.Matrix.Identity();
  75292. var viewProjection = BABYLON.Matrix.Identity();
  75293. var screenSize = BABYLON.Vector2.Zero();
  75294. this.motionBlurPostProcess.onApply = function (effect) {
  75295. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75296. viewProjection.invertToRef(invViewProjection);
  75297. effect.setMatrix("inverseViewProjection", invViewProjection);
  75298. effect.setMatrix("prevViewProjection", prevViewProjection);
  75299. prevViewProjection = viewProjection;
  75300. screenSize.x = _this.motionBlurPostProcess.width;
  75301. screenSize.y = _this.motionBlurPostProcess.height;
  75302. effect.setVector2("screenSize", screenSize);
  75303. motionScale = scene.getEngine().getFps() / 60.0;
  75304. effect.setFloat("motionScale", motionScale);
  75305. effect.setFloat("motionStrength", _this.motionStrength);
  75306. effect.setTexture("depthSampler", _this._getDepthTexture());
  75307. };
  75308. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75309. };
  75310. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75311. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75312. var renderer = this._scene.enableGeometryBufferRenderer();
  75313. return renderer.getGBuffer().textures[0];
  75314. }
  75315. return this._scene.enableDepthRenderer().getDepthMap();
  75316. };
  75317. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75318. for (var i = 0; i < this._cameras.length; i++) {
  75319. var camera = this._cameras[i];
  75320. if (this.originalPostProcess) {
  75321. this.originalPostProcess.dispose(camera);
  75322. }
  75323. if (this.downSampleX4PostProcess) {
  75324. this.downSampleX4PostProcess.dispose(camera);
  75325. }
  75326. if (this.brightPassPostProcess) {
  75327. this.brightPassPostProcess.dispose(camera);
  75328. }
  75329. if (this.textureAdderPostProcess) {
  75330. this.textureAdderPostProcess.dispose(camera);
  75331. }
  75332. if (this.textureAdderFinalPostProcess) {
  75333. this.textureAdderFinalPostProcess.dispose(camera);
  75334. }
  75335. if (this.volumetricLightPostProcess) {
  75336. this.volumetricLightPostProcess.dispose(camera);
  75337. }
  75338. if (this.volumetricLightSmoothXPostProcess) {
  75339. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75340. }
  75341. if (this.volumetricLightSmoothYPostProcess) {
  75342. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75343. }
  75344. if (this.volumetricLightMergePostProces) {
  75345. this.volumetricLightMergePostProces.dispose(camera);
  75346. }
  75347. if (this.volumetricLightFinalPostProcess) {
  75348. this.volumetricLightFinalPostProcess.dispose(camera);
  75349. }
  75350. if (this.lensFlarePostProcess) {
  75351. this.lensFlarePostProcess.dispose(camera);
  75352. }
  75353. if (this.lensFlareComposePostProcess) {
  75354. this.lensFlareComposePostProcess.dispose(camera);
  75355. }
  75356. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75357. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75358. }
  75359. if (this.luminancePostProcess) {
  75360. this.luminancePostProcess.dispose(camera);
  75361. }
  75362. if (this.hdrPostProcess) {
  75363. this.hdrPostProcess.dispose(camera);
  75364. }
  75365. if (this.hdrFinalPostProcess) {
  75366. this.hdrFinalPostProcess.dispose(camera);
  75367. }
  75368. if (this.depthOfFieldPostProcess) {
  75369. this.depthOfFieldPostProcess.dispose(camera);
  75370. }
  75371. if (this.motionBlurPostProcess) {
  75372. this.motionBlurPostProcess.dispose(camera);
  75373. }
  75374. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75375. this.blurHPostProcesses[j].dispose(camera);
  75376. }
  75377. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75378. this.blurVPostProcesses[j].dispose(camera);
  75379. }
  75380. }
  75381. this.originalPostProcess = null;
  75382. this.downSampleX4PostProcess = null;
  75383. this.brightPassPostProcess = null;
  75384. this.textureAdderPostProcess = null;
  75385. this.textureAdderFinalPostProcess = null;
  75386. this.volumetricLightPostProcess = null;
  75387. this.volumetricLightSmoothXPostProcess = null;
  75388. this.volumetricLightSmoothYPostProcess = null;
  75389. this.volumetricLightMergePostProces = null;
  75390. this.volumetricLightFinalPostProcess = null;
  75391. this.lensFlarePostProcess = null;
  75392. this.lensFlareComposePostProcess = null;
  75393. this.luminancePostProcess = null;
  75394. this.hdrPostProcess = null;
  75395. this.hdrFinalPostProcess = null;
  75396. this.depthOfFieldPostProcess = null;
  75397. this.motionBlurPostProcess = null;
  75398. this.luminanceDownSamplePostProcesses = [];
  75399. this.blurHPostProcesses = [];
  75400. this.blurVPostProcesses = [];
  75401. };
  75402. /**
  75403. * Dispose of the pipeline and stop all post processes
  75404. */
  75405. StandardRenderingPipeline.prototype.dispose = function () {
  75406. this._disposePostProcesses();
  75407. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75408. _super.prototype.dispose.call(this);
  75409. };
  75410. /**
  75411. * Serialize the rendering pipeline (Used when exporting)
  75412. * @returns the serialized object
  75413. */
  75414. StandardRenderingPipeline.prototype.serialize = function () {
  75415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75416. if (this.sourceLight) {
  75417. serializationObject.sourceLightId = this.sourceLight.id;
  75418. }
  75419. serializationObject.customType = "StandardRenderingPipeline";
  75420. return serializationObject;
  75421. };
  75422. /**
  75423. * Parse the serialized pipeline
  75424. * @param source Source pipeline.
  75425. * @param scene The scene to load the pipeline to.
  75426. * @param rootUrl The URL of the serialized pipeline.
  75427. * @returns An instantiated pipeline from the serialized object.
  75428. */
  75429. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75430. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75431. if (source.sourceLightId) {
  75432. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75433. }
  75434. return p;
  75435. };
  75436. // Luminance steps
  75437. StandardRenderingPipeline.LuminanceSteps = 6;
  75438. __decorate([
  75439. BABYLON.serialize()
  75440. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75441. __decorate([
  75442. BABYLON.serialize()
  75443. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75444. __decorate([
  75445. BABYLON.serialize()
  75446. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75447. __decorate([
  75448. BABYLON.serialize()
  75449. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75450. __decorate([
  75451. BABYLON.serializeAsTexture("lensTexture")
  75452. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75453. __decorate([
  75454. BABYLON.serialize()
  75455. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75456. __decorate([
  75457. BABYLON.serialize()
  75458. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75459. __decorate([
  75460. BABYLON.serialize()
  75461. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75462. __decorate([
  75463. BABYLON.serialize()
  75464. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75465. __decorate([
  75466. BABYLON.serialize()
  75467. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75468. __decorate([
  75469. BABYLON.serialize()
  75470. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75471. __decorate([
  75472. BABYLON.serializeAsTexture("lensColorTexture")
  75473. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75474. __decorate([
  75475. BABYLON.serialize()
  75476. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75477. __decorate([
  75478. BABYLON.serialize()
  75479. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75480. __decorate([
  75481. BABYLON.serialize()
  75482. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75483. __decorate([
  75484. BABYLON.serialize()
  75485. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75486. __decorate([
  75487. BABYLON.serializeAsTexture("lensStarTexture")
  75488. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75489. __decorate([
  75490. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75491. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75492. __decorate([
  75493. BABYLON.serialize()
  75494. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75495. __decorate([
  75496. BABYLON.serialize()
  75497. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75498. __decorate([
  75499. BABYLON.serialize()
  75500. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75501. __decorate([
  75502. BABYLON.serialize()
  75503. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75504. __decorate([
  75505. BABYLON.serialize()
  75506. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75507. __decorate([
  75508. BABYLON.serialize()
  75509. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75510. __decorate([
  75511. BABYLON.serialize()
  75512. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75513. __decorate([
  75514. BABYLON.serialize()
  75515. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75516. __decorate([
  75517. BABYLON.serialize()
  75518. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75519. __decorate([
  75520. BABYLON.serialize()
  75521. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75522. __decorate([
  75523. BABYLON.serialize()
  75524. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75525. __decorate([
  75526. BABYLON.serialize()
  75527. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75528. return StandardRenderingPipeline;
  75529. }(BABYLON.PostProcessRenderPipeline));
  75530. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75531. })(BABYLON || (BABYLON = {}));
  75532. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75533. var BABYLON;
  75534. (function (BABYLON) {
  75535. var FxaaPostProcess = /** @class */ (function (_super) {
  75536. __extends(FxaaPostProcess, _super);
  75537. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75538. if (camera === void 0) { camera = null; }
  75539. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75540. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75541. var defines = _this._getDefines();
  75542. _this.updateEffect(defines);
  75543. _this.onApplyObservable.add(function (effect) {
  75544. var texelSize = _this.texelSize;
  75545. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75546. });
  75547. return _this;
  75548. }
  75549. FxaaPostProcess.prototype._getDefines = function () {
  75550. var engine = this.getEngine();
  75551. if (!engine) {
  75552. return null;
  75553. }
  75554. var glInfo = engine.getGlInfo();
  75555. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75556. return "#define MALI 1\n";
  75557. }
  75558. return null;
  75559. };
  75560. return FxaaPostProcess;
  75561. }(BABYLON.PostProcess));
  75562. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75563. })(BABYLON || (BABYLON = {}));
  75564. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75565. var BABYLON;
  75566. (function (BABYLON) {
  75567. /**
  75568. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75569. */
  75570. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75571. __extends(ChromaticAberrationPostProcess, _super);
  75572. /**
  75573. * Creates a new instance ChromaticAberrationPostProcess
  75574. * @param name The name of the effect.
  75575. * @param screenWidth The width of the screen to apply the effect on.
  75576. * @param screenHeight The height of the screen to apply the effect on.
  75577. * @param options The required width/height ratio to downsize to before computing the render pass.
  75578. * @param camera The camera to apply the render pass to.
  75579. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75580. * @param engine The engine which the post process will be applied. (default: current engine)
  75581. * @param reusable If the post process can be reused on the same frame. (default: false)
  75582. * @param textureType Type of textures used when performing the post process. (default: 0)
  75583. * @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)
  75584. */
  75585. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75586. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75587. if (blockCompilation === void 0) { blockCompilation = false; }
  75588. 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;
  75589. /**
  75590. * The amount of seperation of rgb channels (default: 30)
  75591. */
  75592. _this.aberrationAmount = 30;
  75593. /**
  75594. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75595. */
  75596. _this.radialIntensity = 0;
  75597. /**
  75598. * 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))
  75599. */
  75600. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75601. /**
  75602. * 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))
  75603. */
  75604. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75605. _this.onApplyObservable.add(function (effect) {
  75606. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75607. effect.setFloat('screen_width', screenWidth);
  75608. effect.setFloat('screen_height', screenHeight);
  75609. effect.setFloat('radialIntensity', _this.radialIntensity);
  75610. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75611. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75612. });
  75613. return _this;
  75614. }
  75615. return ChromaticAberrationPostProcess;
  75616. }(BABYLON.PostProcess));
  75617. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75618. })(BABYLON || (BABYLON = {}));
  75619. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75620. var BABYLON;
  75621. (function (BABYLON) {
  75622. /**
  75623. * The GrainPostProcess adds noise to the image at mid luminance levels
  75624. */
  75625. var GrainPostProcess = /** @class */ (function (_super) {
  75626. __extends(GrainPostProcess, _super);
  75627. /**
  75628. * Creates a new instance of @see GrainPostProcess
  75629. * @param name The name of the effect.
  75630. * @param options The required width/height ratio to downsize to before computing the render pass.
  75631. * @param camera The camera to apply the render pass to.
  75632. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75633. * @param engine The engine which the post process will be applied. (default: current engine)
  75634. * @param reusable If the post process can be reused on the same frame. (default: false)
  75635. * @param textureType Type of textures used when performing the post process. (default: 0)
  75636. * @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)
  75637. */
  75638. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75639. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75640. if (blockCompilation === void 0) { blockCompilation = false; }
  75641. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75642. /**
  75643. * The intensity of the grain added (default: 30)
  75644. */
  75645. _this.intensity = 30;
  75646. /**
  75647. * If the grain should be randomized on every frame
  75648. */
  75649. _this.animated = false;
  75650. _this.onApplyObservable.add(function (effect) {
  75651. effect.setFloat('intensity', _this.intensity);
  75652. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75653. });
  75654. return _this;
  75655. }
  75656. return GrainPostProcess;
  75657. }(BABYLON.PostProcess));
  75658. BABYLON.GrainPostProcess = GrainPostProcess;
  75659. })(BABYLON || (BABYLON = {}));
  75660. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75661. var BABYLON;
  75662. (function (BABYLON) {
  75663. /**
  75664. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75665. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75666. */
  75667. var SharpenPostProcess = /** @class */ (function (_super) {
  75668. __extends(SharpenPostProcess, _super);
  75669. /**
  75670. * Creates a new instance ConvolutionPostProcess
  75671. * @param name The name of the effect.
  75672. * @param options The required width/height ratio to downsize to before computing the render pass.
  75673. * @param camera The camera to apply the render pass to.
  75674. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75675. * @param engine The engine which the post process will be applied. (default: current engine)
  75676. * @param reusable If the post process can be reused on the same frame. (default: false)
  75677. * @param textureType Type of textures used when performing the post process. (default: 0)
  75678. * @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)
  75679. */
  75680. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75682. if (blockCompilation === void 0) { blockCompilation = false; }
  75683. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75684. /**
  75685. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75686. */
  75687. _this.colorAmount = 1.0;
  75688. /**
  75689. * How much sharpness should be applied (default: 0.3)
  75690. */
  75691. _this.edgeAmount = 0.3;
  75692. _this.onApply = function (effect) {
  75693. effect.setFloat2("screenSize", _this.width, _this.height);
  75694. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75695. };
  75696. return _this;
  75697. }
  75698. return SharpenPostProcess;
  75699. }(BABYLON.PostProcess));
  75700. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75701. })(BABYLON || (BABYLON = {}));
  75702. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75703. var BABYLON;
  75704. (function (BABYLON) {
  75705. /**
  75706. * The Blur Post Process which blurs an image based on a kernel and direction.
  75707. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75708. */
  75709. var BlurPostProcess = /** @class */ (function (_super) {
  75710. __extends(BlurPostProcess, _super);
  75711. /**
  75712. * Creates a new instance BlurPostProcess
  75713. * @param name The name of the effect.
  75714. * @param direction The direction in which to blur the image.
  75715. * @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.
  75716. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75717. * @param camera The camera to apply the render pass to.
  75718. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75719. * @param engine The engine which the post process will be applied. (default: current engine)
  75720. * @param reusable If the post process can be reused on the same frame. (default: false)
  75721. * @param textureType Type of textures used when performing the post process. (default: 0)
  75722. * @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)
  75723. */
  75724. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75727. if (defines === void 0) { defines = ""; }
  75728. if (blockCompilation === void 0) { blockCompilation = false; }
  75729. 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;
  75730. _this.direction = direction;
  75731. _this.blockCompilation = blockCompilation;
  75732. _this._packedFloat = false;
  75733. _this._staticDefines = "";
  75734. _this._staticDefines = defines;
  75735. _this.onApplyObservable.add(function (effect) {
  75736. if (_this._outputTexture) {
  75737. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75738. }
  75739. else {
  75740. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75741. }
  75742. });
  75743. _this.kernel = kernel;
  75744. return _this;
  75745. }
  75746. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75747. /**
  75748. * Gets the length in pixels of the blur sample region
  75749. */
  75750. get: function () {
  75751. return this._idealKernel;
  75752. },
  75753. /**
  75754. * Sets the length in pixels of the blur sample region
  75755. */
  75756. set: function (v) {
  75757. if (this._idealKernel === v) {
  75758. return;
  75759. }
  75760. v = Math.max(v, 1);
  75761. this._idealKernel = v;
  75762. this._kernel = this._nearestBestKernel(v);
  75763. if (!this.blockCompilation) {
  75764. this._updateParameters();
  75765. }
  75766. },
  75767. enumerable: true,
  75768. configurable: true
  75769. });
  75770. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75771. /**
  75772. * Gets wether or not the blur is unpacking/repacking floats
  75773. */
  75774. get: function () {
  75775. return this._packedFloat;
  75776. },
  75777. /**
  75778. * Sets wether or not the blur needs to unpack/repack floats
  75779. */
  75780. set: function (v) {
  75781. if (this._packedFloat === v) {
  75782. return;
  75783. }
  75784. this._packedFloat = v;
  75785. if (!this.blockCompilation) {
  75786. this._updateParameters();
  75787. }
  75788. },
  75789. enumerable: true,
  75790. configurable: true
  75791. });
  75792. /**
  75793. * Updates the effect with the current post process compile time values and recompiles the shader.
  75794. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75795. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75796. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75797. * @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
  75798. * @param onCompiled Called when the shader has been compiled.
  75799. * @param onError Called if there is an error when compiling a shader.
  75800. */
  75801. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75802. if (defines === void 0) { defines = null; }
  75803. if (uniforms === void 0) { uniforms = null; }
  75804. if (samplers === void 0) { samplers = null; }
  75805. this._updateParameters(onCompiled, onError);
  75806. };
  75807. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75808. // Generate sampling offsets and weights
  75809. var N = this._kernel;
  75810. var centerIndex = (N - 1) / 2;
  75811. // Generate Gaussian sampling weights over kernel
  75812. var offsets = [];
  75813. var weights = [];
  75814. var totalWeight = 0;
  75815. for (var i = 0; i < N; i++) {
  75816. var u = i / (N - 1);
  75817. var w = this._gaussianWeight(u * 2.0 - 1);
  75818. offsets[i] = (i - centerIndex);
  75819. weights[i] = w;
  75820. totalWeight += w;
  75821. }
  75822. // Normalize weights
  75823. for (var i = 0; i < weights.length; i++) {
  75824. weights[i] /= totalWeight;
  75825. }
  75826. // Optimize: combine samples to take advantage of hardware linear sampling
  75827. // Walk from left to center, combining pairs (symmetrically)
  75828. var linearSamplingWeights = [];
  75829. var linearSamplingOffsets = [];
  75830. var linearSamplingMap = [];
  75831. for (var i = 0; i <= centerIndex; i += 2) {
  75832. var j = Math.min(i + 1, Math.floor(centerIndex));
  75833. var singleCenterSample = i === j;
  75834. if (singleCenterSample) {
  75835. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75836. }
  75837. else {
  75838. var sharedCell = j === centerIndex;
  75839. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75840. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75841. if (offsetLinear === 0) {
  75842. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75843. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75844. }
  75845. else {
  75846. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75847. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75848. }
  75849. }
  75850. }
  75851. for (var i = 0; i < linearSamplingMap.length; i++) {
  75852. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75853. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75854. }
  75855. // Replace with optimized
  75856. offsets = linearSamplingOffsets;
  75857. weights = linearSamplingWeights;
  75858. // Generate shaders
  75859. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75860. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75861. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75862. var defines = "";
  75863. defines += this._staticDefines;
  75864. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75865. if (this._staticDefines.indexOf("DOF") != -1) {
  75866. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75867. varyingCount--;
  75868. }
  75869. for (var i = 0; i < varyingCount; i++) {
  75870. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75871. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75872. }
  75873. var depCount = 0;
  75874. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75875. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75876. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75877. depCount++;
  75878. }
  75879. if (this.packedFloat) {
  75880. defines += "#define PACKEDFLOAT 1";
  75881. }
  75882. this.blockCompilation = false;
  75883. _super.prototype.updateEffect.call(this, defines, null, null, {
  75884. varyingCount: varyingCount,
  75885. depCount: depCount
  75886. }, onCompiled, onError);
  75887. };
  75888. /**
  75889. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75890. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75891. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75892. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75893. * The gaps between physical kernels are compensated for in the weighting of the samples
  75894. * @param idealKernel Ideal blur kernel.
  75895. * @return Nearest best kernel.
  75896. */
  75897. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75898. var v = Math.round(idealKernel);
  75899. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75900. var k = _a[_i];
  75901. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75902. return Math.max(k, 3);
  75903. }
  75904. }
  75905. return Math.max(v, 3);
  75906. };
  75907. /**
  75908. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75909. * @param x The point on the Gaussian distribution to sample.
  75910. * @return the value of the Gaussian function at x.
  75911. */
  75912. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75913. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75914. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75915. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75916. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75917. // truncated at around 1.3% of peak strength.
  75918. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75919. var sigma = (1 / 3);
  75920. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75921. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75922. var weight = (1.0 / denominator) * Math.exp(exponent);
  75923. return weight;
  75924. };
  75925. /**
  75926. * Generates a string that can be used as a floating point number in GLSL.
  75927. * @param x Value to print.
  75928. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75929. * @return GLSL float string.
  75930. */
  75931. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75932. if (decimalFigures === void 0) { decimalFigures = 8; }
  75933. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75934. };
  75935. return BlurPostProcess;
  75936. }(BABYLON.PostProcess));
  75937. BABYLON.BlurPostProcess = BlurPostProcess;
  75938. })(BABYLON || (BABYLON = {}));
  75939. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75940. var BABYLON;
  75941. (function (BABYLON) {
  75942. /**
  75943. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75944. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75945. * based on samples that have a large difference in distance than the center pixel.
  75946. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75947. */
  75948. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75949. __extends(DepthOfFieldBlurPostProcess, _super);
  75950. /**
  75951. * Creates a new instance CircleOfConfusionPostProcess
  75952. * @param name The name of the effect.
  75953. * @param scene The scene the effect belongs to.
  75954. * @param direction The direction the blur should be applied.
  75955. * @param kernel The size of the kernel used to blur.
  75956. * @param options The required width/height ratio to downsize to before computing the render pass.
  75957. * @param camera The camera to apply the render pass to.
  75958. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75959. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75960. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75961. * @param engine The engine which the post process will be applied. (default: current engine)
  75962. * @param reusable If the post process can be reused on the same frame. (default: false)
  75963. * @param textureType Type of textures used when performing the post process. (default: 0)
  75964. * @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)
  75965. */
  75966. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75967. if (imageToBlur === void 0) { imageToBlur = null; }
  75968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75969. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75970. if (blockCompilation === void 0) { blockCompilation = false; }
  75971. 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;
  75972. _this.direction = direction;
  75973. _this.onApplyObservable.add(function (effect) {
  75974. if (imageToBlur != null) {
  75975. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75976. }
  75977. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75978. if (scene.activeCamera) {
  75979. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75980. }
  75981. });
  75982. return _this;
  75983. }
  75984. return DepthOfFieldBlurPostProcess;
  75985. }(BABYLON.BlurPostProcess));
  75986. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75987. })(BABYLON || (BABYLON = {}));
  75988. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75989. var BABYLON;
  75990. (function (BABYLON) {
  75991. /**
  75992. * Options to be set when merging outputs from the default pipeline.
  75993. */
  75994. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75995. function DepthOfFieldMergePostProcessOptions() {
  75996. }
  75997. return DepthOfFieldMergePostProcessOptions;
  75998. }());
  75999. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  76000. /**
  76001. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76002. */
  76003. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  76004. __extends(DepthOfFieldMergePostProcess, _super);
  76005. /**
  76006. * Creates a new instance of DepthOfFieldMergePostProcess
  76007. * @param name The name of the effect.
  76008. * @param originalFromInput Post process which's input will be used for the merge.
  76009. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  76010. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  76011. * @param options The required width/height ratio to downsize to before computing the render pass.
  76012. * @param camera The camera to apply the render pass to.
  76013. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76014. * @param engine The engine which the post process will be applied. (default: current engine)
  76015. * @param reusable If the post process can be reused on the same frame. (default: false)
  76016. * @param textureType Type of textures used when performing the post process. (default: 0)
  76017. * @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)
  76018. */
  76019. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76020. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76021. if (blockCompilation === void 0) { blockCompilation = false; }
  76022. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76023. _this.blurSteps = blurSteps;
  76024. _this.onApplyObservable.add(function (effect) {
  76025. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76026. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76027. blurSteps.forEach(function (step, index) {
  76028. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  76029. });
  76030. });
  76031. if (!blockCompilation) {
  76032. _this.updateEffect();
  76033. }
  76034. return _this;
  76035. }
  76036. /**
  76037. * Updates the effect with the current post process compile time values and recompiles the shader.
  76038. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76039. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76040. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76041. * @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
  76042. * @param onCompiled Called when the shader has been compiled.
  76043. * @param onError Called if there is an error when compiling a shader.
  76044. */
  76045. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76046. if (defines === void 0) { defines = null; }
  76047. if (uniforms === void 0) { uniforms = null; }
  76048. if (samplers === void 0) { samplers = null; }
  76049. if (!defines) {
  76050. defines = "";
  76051. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76052. }
  76053. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76054. };
  76055. return DepthOfFieldMergePostProcess;
  76056. }(BABYLON.PostProcess));
  76057. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76058. })(BABYLON || (BABYLON = {}));
  76059. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76060. var BABYLON;
  76061. (function (BABYLON) {
  76062. /**
  76063. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76064. */
  76065. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76066. __extends(CircleOfConfusionPostProcess, _super);
  76067. /**
  76068. * Creates a new instance CircleOfConfusionPostProcess
  76069. * @param name The name of the effect.
  76070. * @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.
  76071. * @param options The required width/height ratio to downsize to before computing the render pass.
  76072. * @param camera The camera to apply the render pass to.
  76073. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76074. * @param engine The engine which the post process will be applied. (default: current engine)
  76075. * @param reusable If the post process can be reused on the same frame. (default: false)
  76076. * @param textureType Type of textures used when performing the post process. (default: 0)
  76077. * @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)
  76078. */
  76079. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76080. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76081. if (blockCompilation === void 0) { blockCompilation = false; }
  76082. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76083. /**
  76084. * 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.
  76085. */
  76086. _this.lensSize = 50;
  76087. /**
  76088. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76089. */
  76090. _this.fStop = 1.4;
  76091. /**
  76092. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76093. */
  76094. _this.focusDistance = 2000;
  76095. /**
  76096. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76097. */
  76098. _this.focalLength = 50;
  76099. _this._depthTexture = null;
  76100. _this._depthTexture = depthTexture;
  76101. _this.onApplyObservable.add(function (effect) {
  76102. if (!_this._depthTexture) {
  76103. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76104. return;
  76105. }
  76106. effect.setTexture("depthSampler", _this._depthTexture);
  76107. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76108. var aperture = _this.lensSize / _this.fStop;
  76109. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76110. effect.setFloat('focusDistance', _this.focusDistance);
  76111. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76112. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76113. });
  76114. return _this;
  76115. }
  76116. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76117. /**
  76118. * 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.
  76119. */
  76120. set: function (value) {
  76121. this._depthTexture = value;
  76122. },
  76123. enumerable: true,
  76124. configurable: true
  76125. });
  76126. return CircleOfConfusionPostProcess;
  76127. }(BABYLON.PostProcess));
  76128. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76129. })(BABYLON || (BABYLON = {}));
  76130. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76131. var BABYLON;
  76132. (function (BABYLON) {
  76133. /**
  76134. * Specifies the level of max blur that should be applied when using the depth of field effect
  76135. */
  76136. var DepthOfFieldEffectBlurLevel;
  76137. (function (DepthOfFieldEffectBlurLevel) {
  76138. /**
  76139. * Subtle blur
  76140. */
  76141. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76142. /**
  76143. * Medium blur
  76144. */
  76145. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76146. /**
  76147. * Large blur
  76148. */
  76149. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76150. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76151. ;
  76152. /**
  76153. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76154. */
  76155. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76156. __extends(DepthOfFieldEffect, _super);
  76157. /**
  76158. * Creates a new instance DepthOfFieldEffect
  76159. * @param scene The scene the effect belongs to.
  76160. * @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.
  76161. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76162. * @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)
  76163. */
  76164. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76165. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76166. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76167. if (blockCompilation === void 0) { blockCompilation = false; }
  76168. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76169. return _this._effects;
  76170. }, true) || this;
  76171. /**
  76172. * Internal post processes in depth of field effect
  76173. */
  76174. _this._effects = [];
  76175. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76176. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76177. // 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)
  76178. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76179. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76180. _this._depthOfFieldBlurY = [];
  76181. _this._depthOfFieldBlurX = [];
  76182. var blurCount = 1;
  76183. var kernelSize = 15;
  76184. switch (blurLevel) {
  76185. case DepthOfFieldEffectBlurLevel.High: {
  76186. blurCount = 3;
  76187. kernelSize = 51;
  76188. break;
  76189. }
  76190. case DepthOfFieldEffectBlurLevel.Medium: {
  76191. blurCount = 2;
  76192. kernelSize = 31;
  76193. break;
  76194. }
  76195. default: {
  76196. kernelSize = 15;
  76197. blurCount = 1;
  76198. break;
  76199. }
  76200. }
  76201. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76202. var ratio = 1.0;
  76203. for (var i = 0; i < blurCount; i++) {
  76204. 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);
  76205. blurY.autoClear = false;
  76206. ratio = 0.75 / Math.pow(2, i);
  76207. 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);
  76208. blurX.autoClear = false;
  76209. _this._depthOfFieldBlurY.push(blurY);
  76210. _this._depthOfFieldBlurX.push(blurX);
  76211. }
  76212. // Set all post processes on the effect.
  76213. _this._effects = [_this._circleOfConfusion];
  76214. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76215. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76216. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76217. }
  76218. // Merge blurred images with original image based on circleOfConfusion
  76219. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76220. _this._dofMerge.autoClear = false;
  76221. _this._effects.push(_this._dofMerge);
  76222. return _this;
  76223. }
  76224. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76225. get: function () {
  76226. return this._circleOfConfusion.focalLength;
  76227. },
  76228. /**
  76229. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76230. */
  76231. set: function (value) {
  76232. this._circleOfConfusion.focalLength = value;
  76233. },
  76234. enumerable: true,
  76235. configurable: true
  76236. });
  76237. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76238. get: function () {
  76239. return this._circleOfConfusion.fStop;
  76240. },
  76241. /**
  76242. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76243. */
  76244. set: function (value) {
  76245. this._circleOfConfusion.fStop = value;
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76251. get: function () {
  76252. return this._circleOfConfusion.focusDistance;
  76253. },
  76254. /**
  76255. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76256. */
  76257. set: function (value) {
  76258. this._circleOfConfusion.focusDistance = value;
  76259. },
  76260. enumerable: true,
  76261. configurable: true
  76262. });
  76263. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76264. get: function () {
  76265. return this._circleOfConfusion.lensSize;
  76266. },
  76267. /**
  76268. * 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.
  76269. */
  76270. set: function (value) {
  76271. this._circleOfConfusion.lensSize = value;
  76272. },
  76273. enumerable: true,
  76274. configurable: true
  76275. });
  76276. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76277. /**
  76278. * 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.
  76279. */
  76280. set: function (value) {
  76281. this._circleOfConfusion.depthTexture = value;
  76282. },
  76283. enumerable: true,
  76284. configurable: true
  76285. });
  76286. /**
  76287. * Disposes each of the internal effects for a given camera.
  76288. * @param camera The camera to dispose the effect on.
  76289. */
  76290. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76291. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76292. this._effects[effectIndex].dispose(camera);
  76293. }
  76294. };
  76295. /**
  76296. * Internal
  76297. */
  76298. DepthOfFieldEffect.prototype._updateEffects = function () {
  76299. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76300. this._effects[effectIndex].updateEffect();
  76301. }
  76302. };
  76303. /**
  76304. * Internal
  76305. * @returns if all the contained post processes are ready.
  76306. */
  76307. DepthOfFieldEffect.prototype._isReady = function () {
  76308. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76309. if (!this._effects[effectIndex].isReady()) {
  76310. return false;
  76311. }
  76312. }
  76313. return true;
  76314. };
  76315. return DepthOfFieldEffect;
  76316. }(BABYLON.PostProcessRenderEffect));
  76317. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76318. })(BABYLON || (BABYLON = {}));
  76319. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76320. var BABYLON;
  76321. (function (BABYLON) {
  76322. /**
  76323. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76324. */
  76325. var BloomMergePostProcess = /** @class */ (function (_super) {
  76326. __extends(BloomMergePostProcess, _super);
  76327. /**
  76328. * Creates a new instance of @see BloomMergePostProcess
  76329. * @param name The name of the effect.
  76330. * @param originalFromInput Post process which's input will be used for the merge.
  76331. * @param blurred Blurred highlights post process which's output will be used.
  76332. * @param weight Weight of the bloom to be added to the original input.
  76333. * @param options The required width/height ratio to downsize to before computing the render pass.
  76334. * @param camera The camera to apply the render pass to.
  76335. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76336. * @param engine The engine which the post process will be applied. (default: current engine)
  76337. * @param reusable If the post process can be reused on the same frame. (default: false)
  76338. * @param textureType Type of textures used when performing the post process. (default: 0)
  76339. * @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)
  76340. */
  76341. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76342. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76343. if (blockCompilation === void 0) { blockCompilation = false; }
  76344. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76345. _this.weight = weight;
  76346. _this.onApplyObservable.add(function (effect) {
  76347. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76348. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76349. effect.setFloat("bloomWeight", _this.weight);
  76350. });
  76351. if (!blockCompilation) {
  76352. _this.updateEffect();
  76353. }
  76354. return _this;
  76355. }
  76356. return BloomMergePostProcess;
  76357. }(BABYLON.PostProcess));
  76358. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76359. })(BABYLON || (BABYLON = {}));
  76360. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76361. var BABYLON;
  76362. (function (BABYLON) {
  76363. /**
  76364. * 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.
  76365. */
  76366. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76367. __extends(ExtractHighlightsPostProcess, _super);
  76368. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76369. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76370. if (blockCompilation === void 0) { blockCompilation = false; }
  76371. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76372. /**
  76373. * The luminance threshold, pixels below this value will be set to black.
  76374. */
  76375. _this.threshold = 0.9;
  76376. /**
  76377. * Internal
  76378. */
  76379. _this._exposure = 1;
  76380. /**
  76381. * Post process which has the input texture to be used when performing highlight extraction
  76382. */
  76383. _this._inputPostProcess = null;
  76384. _this.onApplyObservable.add(function (effect) {
  76385. if (_this._inputPostProcess) {
  76386. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76387. }
  76388. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76389. effect.setFloat('exposure', _this._exposure);
  76390. });
  76391. return _this;
  76392. }
  76393. return ExtractHighlightsPostProcess;
  76394. }(BABYLON.PostProcess));
  76395. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76396. })(BABYLON || (BABYLON = {}));
  76397. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76398. var BABYLON;
  76399. (function (BABYLON) {
  76400. /**
  76401. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76402. */
  76403. var BloomEffect = /** @class */ (function (_super) {
  76404. __extends(BloomEffect, _super);
  76405. /**
  76406. * Creates a new instance of @see BloomEffect
  76407. * @param scene The scene the effect belongs to.
  76408. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76409. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76410. * @param bloomWeight The the strength of bloom.
  76411. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76412. * @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)
  76413. */
  76414. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76415. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76416. if (blockCompilation === void 0) { blockCompilation = false; }
  76417. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76418. return _this._effects;
  76419. }, true) || this;
  76420. _this.bloomScale = bloomScale;
  76421. /**
  76422. * Internal
  76423. */
  76424. _this._effects = [];
  76425. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76426. _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);
  76427. _this._blurX.alwaysForcePOT = true;
  76428. _this._blurX.autoClear = false;
  76429. _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);
  76430. _this._blurY.alwaysForcePOT = true;
  76431. _this._blurY.autoClear = false;
  76432. _this.kernel = bloomKernel;
  76433. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76434. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76435. _this._merge.autoClear = false;
  76436. _this._effects.push(_this._merge);
  76437. return _this;
  76438. }
  76439. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76440. /**
  76441. * The luminance threshold to find bright areas of the image to bloom.
  76442. */
  76443. get: function () {
  76444. return this._downscale.threshold;
  76445. },
  76446. set: function (value) {
  76447. this._downscale.threshold = value;
  76448. },
  76449. enumerable: true,
  76450. configurable: true
  76451. });
  76452. Object.defineProperty(BloomEffect.prototype, "weight", {
  76453. /**
  76454. * The strength of the bloom.
  76455. */
  76456. get: function () {
  76457. return this._merge.weight;
  76458. },
  76459. set: function (value) {
  76460. this._merge.weight = value;
  76461. },
  76462. enumerable: true,
  76463. configurable: true
  76464. });
  76465. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76466. /**
  76467. * Specifies the size of the bloom blur kernel, relative to the final output size
  76468. */
  76469. get: function () {
  76470. return this._blurX.kernel / this.bloomScale;
  76471. },
  76472. set: function (value) {
  76473. this._blurX.kernel = value * this.bloomScale;
  76474. this._blurY.kernel = value * this.bloomScale;
  76475. },
  76476. enumerable: true,
  76477. configurable: true
  76478. });
  76479. /**
  76480. * Disposes each of the internal effects for a given camera.
  76481. * @param camera The camera to dispose the effect on.
  76482. */
  76483. BloomEffect.prototype.disposeEffects = function (camera) {
  76484. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76485. this._effects[effectIndex].dispose(camera);
  76486. }
  76487. };
  76488. /**
  76489. * Internal
  76490. */
  76491. BloomEffect.prototype._updateEffects = function () {
  76492. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76493. this._effects[effectIndex].updateEffect();
  76494. }
  76495. };
  76496. /**
  76497. * Internal
  76498. * @returns if all the contained post processes are ready.
  76499. */
  76500. BloomEffect.prototype._isReady = function () {
  76501. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76502. if (!this._effects[effectIndex].isReady()) {
  76503. return false;
  76504. }
  76505. }
  76506. return true;
  76507. };
  76508. return BloomEffect;
  76509. }(BABYLON.PostProcessRenderEffect));
  76510. BABYLON.BloomEffect = BloomEffect;
  76511. })(BABYLON || (BABYLON = {}));
  76512. //# sourceMappingURL=babylon.bloomEffect.js.map
  76513. var BABYLON;
  76514. (function (BABYLON) {
  76515. /**
  76516. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76517. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76518. */
  76519. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76520. __extends(DefaultRenderingPipeline, _super);
  76521. /**
  76522. * @constructor
  76523. * @param {string} name - The rendering pipeline name (default: "")
  76524. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76525. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76526. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76527. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76528. */
  76529. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76530. if (name === void 0) { name = ""; }
  76531. if (hdr === void 0) { hdr = true; }
  76532. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76533. if (automaticBuild === void 0) { automaticBuild = true; }
  76534. var _this = _super.call(this, scene.getEngine(), name) || this;
  76535. _this._camerasToBeAttached = [];
  76536. /**
  76537. * ID of the sharpen post process,
  76538. */
  76539. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76540. /**
  76541. * ID of the image processing post process;
  76542. */
  76543. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76544. /**
  76545. * ID of the Fast Approximate Anti-Aliasing post process;
  76546. */
  76547. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76548. /**
  76549. * ID of the chromatic aberration post process,
  76550. */
  76551. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76552. /**
  76553. * ID of the grain post process
  76554. */
  76555. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76556. /**
  76557. * Glow post process which adds a glow to emmisive areas of the image
  76558. */
  76559. _this._glowLayer = null;
  76560. /**
  76561. * Animations which can be used to tweak settings over a period of time
  76562. */
  76563. _this.animations = [];
  76564. _this._imageProcessingConfigurationObserver = null;
  76565. // Values
  76566. _this._sharpenEnabled = false;
  76567. _this._bloomEnabled = false;
  76568. _this._depthOfFieldEnabled = false;
  76569. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76570. _this._fxaaEnabled = false;
  76571. _this._imageProcessingEnabled = true;
  76572. _this._bloomScale = 0.5;
  76573. _this._chromaticAberrationEnabled = false;
  76574. _this._grainEnabled = false;
  76575. _this._buildAllowed = true;
  76576. _this._resizeObserver = null;
  76577. _this._hardwareScaleLevel = 1.0;
  76578. _this._bloomKernel = 64;
  76579. /**
  76580. * Specifies the weight of the bloom in the final rendering
  76581. */
  76582. _this._bloomWeight = 0.15;
  76583. /**
  76584. * Specifies the luma threshold for the area that will be blurred by the bloom
  76585. */
  76586. _this._bloomThreshold = 0.9;
  76587. _this._samples = 1;
  76588. _this._hasCleared = false;
  76589. _this._prevPostProcess = null;
  76590. _this._prevPrevPostProcess = null;
  76591. _this._cameras = cameras || scene.cameras;
  76592. _this._camerasToBeAttached = _this._cameras.slice();
  76593. _this._buildAllowed = automaticBuild;
  76594. // Initialize
  76595. _this._scene = scene;
  76596. var caps = _this._scene.getEngine().getCaps();
  76597. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76598. // Misc
  76599. if (_this._hdr) {
  76600. if (caps.textureHalfFloatRender) {
  76601. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76602. }
  76603. else if (caps.textureFloatRender) {
  76604. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76605. }
  76606. }
  76607. else {
  76608. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76609. }
  76610. // Attach
  76611. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76612. var engine = _this._scene.getEngine();
  76613. // Create post processes before hand so they can be modified before enabled.
  76614. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76615. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76616. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76617. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76618. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76619. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76620. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76621. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76622. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76623. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76624. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76625. _this.bloomKernel = _this.bloomKernel;
  76626. });
  76627. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76628. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76629. });
  76630. _this._buildPipeline();
  76631. return _this;
  76632. }
  76633. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76634. get: function () {
  76635. return this._sharpenEnabled;
  76636. },
  76637. /**
  76638. * Enable or disable the sharpen process from the pipeline
  76639. */
  76640. set: function (enabled) {
  76641. if (this._sharpenEnabled === enabled) {
  76642. return;
  76643. }
  76644. this._sharpenEnabled = enabled;
  76645. this._buildPipeline();
  76646. },
  76647. enumerable: true,
  76648. configurable: true
  76649. });
  76650. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76651. /**
  76652. * Specifies the size of the bloom blur kernel, relative to the final output size
  76653. */
  76654. get: function () {
  76655. return this._bloomKernel;
  76656. },
  76657. set: function (value) {
  76658. this._bloomKernel = value;
  76659. this.bloom.kernel = value / this._hardwareScaleLevel;
  76660. },
  76661. enumerable: true,
  76662. configurable: true
  76663. });
  76664. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76665. get: function () {
  76666. return this._bloomWeight;
  76667. },
  76668. /**
  76669. * The strength of the bloom.
  76670. */
  76671. set: function (value) {
  76672. if (this._bloomWeight === value) {
  76673. return;
  76674. }
  76675. this.bloom.weight = value;
  76676. this._bloomWeight = value;
  76677. },
  76678. enumerable: true,
  76679. configurable: true
  76680. });
  76681. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76682. get: function () {
  76683. return this._bloomThreshold;
  76684. },
  76685. /**
  76686. * The strength of the bloom.
  76687. */
  76688. set: function (value) {
  76689. if (this._bloomThreshold === value) {
  76690. return;
  76691. }
  76692. this.bloom.threshold = value;
  76693. this._bloomThreshold = value;
  76694. },
  76695. enumerable: true,
  76696. configurable: true
  76697. });
  76698. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76699. get: function () {
  76700. return this._bloomScale;
  76701. },
  76702. /**
  76703. * The scale of the bloom, lower value will provide better performance.
  76704. */
  76705. set: function (value) {
  76706. if (this._bloomScale === value) {
  76707. return;
  76708. }
  76709. this._bloomScale = value;
  76710. // recreate bloom and dispose old as this setting is not dynamic
  76711. this._rebuildBloom();
  76712. this._buildPipeline();
  76713. },
  76714. enumerable: true,
  76715. configurable: true
  76716. });
  76717. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76718. get: function () {
  76719. return this._bloomEnabled;
  76720. },
  76721. /**
  76722. * Enable or disable the bloom from the pipeline
  76723. */
  76724. set: function (enabled) {
  76725. if (this._bloomEnabled === enabled) {
  76726. return;
  76727. }
  76728. this._bloomEnabled = enabled;
  76729. this._buildPipeline();
  76730. },
  76731. enumerable: true,
  76732. configurable: true
  76733. });
  76734. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76735. // recreate bloom and dispose old as this setting is not dynamic
  76736. var oldBloom = this.bloom;
  76737. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76738. this.bloom.threshold = oldBloom.threshold;
  76739. for (var i = 0; i < this._cameras.length; i++) {
  76740. oldBloom.disposeEffects(this._cameras[i]);
  76741. }
  76742. };
  76743. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76744. /**
  76745. * If the depth of field is enabled.
  76746. */
  76747. get: function () {
  76748. return this._depthOfFieldEnabled;
  76749. },
  76750. set: function (enabled) {
  76751. if (this._depthOfFieldEnabled === enabled) {
  76752. return;
  76753. }
  76754. this._depthOfFieldEnabled = enabled;
  76755. this._buildPipeline();
  76756. },
  76757. enumerable: true,
  76758. configurable: true
  76759. });
  76760. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76761. /**
  76762. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76763. */
  76764. get: function () {
  76765. return this._depthOfFieldBlurLevel;
  76766. },
  76767. set: function (value) {
  76768. if (this._depthOfFieldBlurLevel === value) {
  76769. return;
  76770. }
  76771. this._depthOfFieldBlurLevel = value;
  76772. // recreate dof and dispose old as this setting is not dynamic
  76773. var oldDof = this.depthOfField;
  76774. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76775. this.depthOfField.focalLength = oldDof.focalLength;
  76776. this.depthOfField.focusDistance = oldDof.focusDistance;
  76777. this.depthOfField.fStop = oldDof.fStop;
  76778. this.depthOfField.lensSize = oldDof.lensSize;
  76779. for (var i = 0; i < this._cameras.length; i++) {
  76780. oldDof.disposeEffects(this._cameras[i]);
  76781. }
  76782. this._buildPipeline();
  76783. },
  76784. enumerable: true,
  76785. configurable: true
  76786. });
  76787. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76788. get: function () {
  76789. return this._fxaaEnabled;
  76790. },
  76791. /**
  76792. * If the anti aliasing is enabled.
  76793. */
  76794. set: function (enabled) {
  76795. if (this._fxaaEnabled === enabled) {
  76796. return;
  76797. }
  76798. this._fxaaEnabled = enabled;
  76799. this._buildPipeline();
  76800. },
  76801. enumerable: true,
  76802. configurable: true
  76803. });
  76804. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76805. get: function () {
  76806. return this._samples;
  76807. },
  76808. /**
  76809. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76810. */
  76811. set: function (sampleCount) {
  76812. if (this._samples === sampleCount) {
  76813. return;
  76814. }
  76815. this._samples = sampleCount;
  76816. this._buildPipeline();
  76817. },
  76818. enumerable: true,
  76819. configurable: true
  76820. });
  76821. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76822. get: function () {
  76823. return this._imageProcessingEnabled;
  76824. },
  76825. /**
  76826. * If image processing is enabled.
  76827. */
  76828. set: function (enabled) {
  76829. if (this._imageProcessingEnabled === enabled) {
  76830. return;
  76831. }
  76832. this._imageProcessingEnabled = enabled;
  76833. this._buildPipeline();
  76834. },
  76835. enumerable: true,
  76836. configurable: true
  76837. });
  76838. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76839. get: function () {
  76840. return this._glowLayer == null;
  76841. },
  76842. /**
  76843. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76844. */
  76845. set: function (enabled) {
  76846. if (enabled && !this._glowLayer) {
  76847. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76848. }
  76849. else if (!enabled && this._glowLayer) {
  76850. this._glowLayer.dispose();
  76851. this._glowLayer = null;
  76852. }
  76853. },
  76854. enumerable: true,
  76855. configurable: true
  76856. });
  76857. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76858. get: function () {
  76859. return this._chromaticAberrationEnabled;
  76860. },
  76861. /**
  76862. * Enable or disable the chromaticAberration process from the pipeline
  76863. */
  76864. set: function (enabled) {
  76865. if (this._chromaticAberrationEnabled === enabled) {
  76866. return;
  76867. }
  76868. this._chromaticAberrationEnabled = enabled;
  76869. this._buildPipeline();
  76870. },
  76871. enumerable: true,
  76872. configurable: true
  76873. });
  76874. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76875. get: function () {
  76876. return this._grainEnabled;
  76877. },
  76878. /**
  76879. * Enable or disable the grain process from the pipeline
  76880. */
  76881. set: function (enabled) {
  76882. if (this._grainEnabled === enabled) {
  76883. return;
  76884. }
  76885. this._grainEnabled = enabled;
  76886. this._buildPipeline();
  76887. },
  76888. enumerable: true,
  76889. configurable: true
  76890. });
  76891. /**
  76892. * Force the compilation of the entire pipeline.
  76893. */
  76894. DefaultRenderingPipeline.prototype.prepare = function () {
  76895. var previousState = this._buildAllowed;
  76896. this._buildAllowed = true;
  76897. this._buildPipeline();
  76898. this._buildAllowed = previousState;
  76899. };
  76900. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76901. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76902. if (this._hasCleared) {
  76903. postProcess.autoClear = false;
  76904. }
  76905. else {
  76906. postProcess.autoClear = true;
  76907. this._scene.autoClear = false;
  76908. this._hasCleared = true;
  76909. }
  76910. if (!skipTextureSharing) {
  76911. if (this._prevPrevPostProcess) {
  76912. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76913. }
  76914. else {
  76915. postProcess.useOwnOutput();
  76916. }
  76917. if (this._prevPostProcess) {
  76918. this._prevPrevPostProcess = this._prevPostProcess;
  76919. }
  76920. this._prevPostProcess = postProcess;
  76921. }
  76922. };
  76923. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76924. var _this = this;
  76925. if (!this._buildAllowed) {
  76926. return;
  76927. }
  76928. this._scene.autoClear = true;
  76929. var engine = this._scene.getEngine();
  76930. this._disposePostProcesses();
  76931. if (this._cameras !== null) {
  76932. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76933. // get back cameras to be used to reattach pipeline
  76934. this._cameras = this._camerasToBeAttached.slice();
  76935. }
  76936. this._reset();
  76937. this._prevPostProcess = null;
  76938. this._prevPrevPostProcess = null;
  76939. this._hasCleared = false;
  76940. if (this.depthOfFieldEnabled) {
  76941. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76942. this.depthOfField.depthTexture = depthTexture;
  76943. if (!this.depthOfField._isReady()) {
  76944. this.depthOfField._updateEffects();
  76945. }
  76946. this.addEffect(this.depthOfField);
  76947. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76948. }
  76949. if (this.bloomEnabled) {
  76950. if (!this.bloom._isReady()) {
  76951. this.bloom._updateEffects();
  76952. }
  76953. this.addEffect(this.bloom);
  76954. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76955. }
  76956. if (this._imageProcessingEnabled) {
  76957. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76958. if (this._hdr) {
  76959. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76960. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76961. }
  76962. else {
  76963. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76964. }
  76965. }
  76966. if (this.sharpenEnabled) {
  76967. if (!this.sharpen.isReady()) {
  76968. this.sharpen.updateEffect();
  76969. }
  76970. this.addEffect(this._sharpenEffect);
  76971. this._setAutoClearAndTextureSharing(this.sharpen);
  76972. }
  76973. if (this.grainEnabled) {
  76974. if (!this.grain.isReady()) {
  76975. this.grain.updateEffect();
  76976. }
  76977. this.addEffect(this._grainEffect);
  76978. this._setAutoClearAndTextureSharing(this.grain);
  76979. }
  76980. if (this.chromaticAberrationEnabled) {
  76981. if (!this.chromaticAberration.isReady()) {
  76982. this.chromaticAberration.updateEffect();
  76983. }
  76984. this.addEffect(this._chromaticAberrationEffect);
  76985. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76986. }
  76987. if (this.fxaaEnabled) {
  76988. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76989. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76990. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76991. }
  76992. if (this._cameras !== null) {
  76993. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76994. }
  76995. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76996. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76997. }
  76998. };
  76999. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  77000. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  77001. for (var i = 0; i < this._cameras.length; i++) {
  77002. var camera = this._cameras[i];
  77003. if (this.imageProcessing) {
  77004. this.imageProcessing.dispose(camera);
  77005. }
  77006. if (this.fxaa) {
  77007. this.fxaa.dispose(camera);
  77008. }
  77009. // These are created in the constructor and should not be disposed on every pipeline change
  77010. if (disposeNonRecreated) {
  77011. if (this.sharpen) {
  77012. this.sharpen.dispose(camera);
  77013. }
  77014. if (this.depthOfField) {
  77015. this.depthOfField.disposeEffects(camera);
  77016. }
  77017. if (this.bloom) {
  77018. this.bloom.disposeEffects(camera);
  77019. }
  77020. if (this.chromaticAberration) {
  77021. this.chromaticAberration.dispose(camera);
  77022. }
  77023. if (this.grain) {
  77024. this.grain.dispose(camera);
  77025. }
  77026. if (this._glowLayer) {
  77027. this._glowLayer.dispose();
  77028. }
  77029. }
  77030. }
  77031. this.imageProcessing = null;
  77032. this.fxaa = null;
  77033. if (disposeNonRecreated) {
  77034. this.sharpen = null;
  77035. this._sharpenEffect = null;
  77036. this.depthOfField = null;
  77037. this.bloom = null;
  77038. this.chromaticAberration = null;
  77039. this._chromaticAberrationEffect = null;
  77040. this.grain = null;
  77041. this._grainEffect = null;
  77042. this._glowLayer = null;
  77043. }
  77044. };
  77045. /**
  77046. * Adds a camera to the pipeline
  77047. * @param camera the camera to be added
  77048. */
  77049. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77050. this._camerasToBeAttached.push(camera);
  77051. this._buildPipeline();
  77052. };
  77053. /**
  77054. * Removes a camera from the pipeline
  77055. * @param camera the camera to remove
  77056. */
  77057. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77058. var index = this._camerasToBeAttached.indexOf(camera);
  77059. this._camerasToBeAttached.splice(index, 1);
  77060. this._buildPipeline();
  77061. };
  77062. /**
  77063. * Dispose of the pipeline and stop all post processes
  77064. */
  77065. DefaultRenderingPipeline.prototype.dispose = function () {
  77066. this._disposePostProcesses(true);
  77067. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77068. this._scene.autoClear = true;
  77069. if (this._resizeObserver) {
  77070. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77071. this._resizeObserver = null;
  77072. }
  77073. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77074. _super.prototype.dispose.call(this);
  77075. };
  77076. /**
  77077. * Serialize the rendering pipeline (Used when exporting)
  77078. * @returns the serialized object
  77079. */
  77080. DefaultRenderingPipeline.prototype.serialize = function () {
  77081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77082. serializationObject.customType = "DefaultRenderingPipeline";
  77083. return serializationObject;
  77084. };
  77085. /**
  77086. * Parse the serialized pipeline
  77087. * @param source Source pipeline.
  77088. * @param scene The scene to load the pipeline to.
  77089. * @param rootUrl The URL of the serialized pipeline.
  77090. * @returns An instantiated pipeline from the serialized object.
  77091. */
  77092. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77093. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77094. };
  77095. __decorate([
  77096. BABYLON.serialize()
  77097. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77098. __decorate([
  77099. BABYLON.serialize()
  77100. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77107. __decorate([
  77108. BABYLON.serialize()
  77109. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77110. __decorate([
  77111. BABYLON.serialize()
  77112. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77113. __decorate([
  77114. BABYLON.serialize()
  77115. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77116. __decorate([
  77117. BABYLON.serialize()
  77118. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77119. __decorate([
  77120. BABYLON.serialize()
  77121. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77122. __decorate([
  77123. BABYLON.serialize()
  77124. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77125. __decorate([
  77126. BABYLON.serialize()
  77127. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77128. __decorate([
  77129. BABYLON.serialize()
  77130. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77131. __decorate([
  77132. BABYLON.serialize()
  77133. ], DefaultRenderingPipeline.prototype, "samples", null);
  77134. __decorate([
  77135. BABYLON.serialize()
  77136. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77137. __decorate([
  77138. BABYLON.serialize()
  77139. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77140. __decorate([
  77141. BABYLON.serialize()
  77142. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77143. __decorate([
  77144. BABYLON.serialize()
  77145. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77146. return DefaultRenderingPipeline;
  77147. }(BABYLON.PostProcessRenderPipeline));
  77148. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77149. })(BABYLON || (BABYLON = {}));
  77150. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77151. var BABYLON;
  77152. (function (BABYLON) {
  77153. /**
  77154. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77155. */
  77156. var GeometryBufferRenderer = /** @class */ (function () {
  77157. /**
  77158. * Creates a new G Buffer for the scene
  77159. * @param scene The scene the buffer belongs to
  77160. * @param ratio How big is the buffer related to the main canvas.
  77161. */
  77162. function GeometryBufferRenderer(scene, ratio) {
  77163. if (ratio === void 0) { ratio = 1; }
  77164. this._enablePosition = false;
  77165. this._scene = scene;
  77166. this._ratio = ratio;
  77167. // Render target
  77168. this._createRenderTargets();
  77169. }
  77170. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77171. /**
  77172. * Set the render list (meshes to be rendered) used in the G buffer.
  77173. */
  77174. set: function (meshes) {
  77175. this._multiRenderTarget.renderList = meshes;
  77176. },
  77177. enumerable: true,
  77178. configurable: true
  77179. });
  77180. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77181. /**
  77182. * Gets wether or not G buffer are supported by the running hardware.
  77183. * This requires draw buffer supports
  77184. */
  77185. get: function () {
  77186. return this._multiRenderTarget.isSupported;
  77187. },
  77188. enumerable: true,
  77189. configurable: true
  77190. });
  77191. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77192. /**
  77193. * Gets wether or not position are enabled for the G buffer.
  77194. */
  77195. get: function () {
  77196. return this._enablePosition;
  77197. },
  77198. /**
  77199. * Sets wether or not position are enabled for the G buffer.
  77200. */
  77201. set: function (enable) {
  77202. this._enablePosition = enable;
  77203. this.dispose();
  77204. this._createRenderTargets();
  77205. },
  77206. enumerable: true,
  77207. configurable: true
  77208. });
  77209. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77210. /**
  77211. * Gets the scene associated with the buffer.
  77212. */
  77213. get: function () {
  77214. return this._scene;
  77215. },
  77216. enumerable: true,
  77217. configurable: true
  77218. });
  77219. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77220. /**
  77221. * Gets the ratio used by the buffer during its creation.
  77222. * How big is the buffer related to the main canvas.
  77223. */
  77224. get: function () {
  77225. return this._ratio;
  77226. },
  77227. enumerable: true,
  77228. configurable: true
  77229. });
  77230. /**
  77231. * Checks wether everything is ready to render a submesh to the G buffer.
  77232. * @param subMesh the submesh to check readiness for
  77233. * @param useInstances is the mesh drawn using instance or not
  77234. * @returns true if ready otherwise false
  77235. */
  77236. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77237. var material = subMesh.getMaterial();
  77238. if (material && material.disableDepthWrite) {
  77239. return false;
  77240. }
  77241. var defines = [];
  77242. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77243. var mesh = subMesh.getMesh();
  77244. // Alpha test
  77245. if (material && material.needAlphaTesting()) {
  77246. defines.push("#define ALPHATEST");
  77247. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77248. attribs.push(BABYLON.VertexBuffer.UVKind);
  77249. defines.push("#define UV1");
  77250. }
  77251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77252. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77253. defines.push("#define UV2");
  77254. }
  77255. }
  77256. // Buffers
  77257. if (this._enablePosition) {
  77258. defines.push("#define POSITION");
  77259. }
  77260. // Bones
  77261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77264. if (mesh.numBoneInfluencers > 4) {
  77265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77267. }
  77268. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77269. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77270. }
  77271. else {
  77272. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77273. }
  77274. // Instances
  77275. if (useInstances) {
  77276. defines.push("#define INSTANCES");
  77277. attribs.push("world0");
  77278. attribs.push("world1");
  77279. attribs.push("world2");
  77280. attribs.push("world3");
  77281. }
  77282. // Get correct effect
  77283. var join = defines.join("\n");
  77284. if (this._cachedDefines !== join) {
  77285. this._cachedDefines = join;
  77286. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77287. }
  77288. return this._effect.isReady();
  77289. };
  77290. /**
  77291. * Gets the current underlying G Buffer.
  77292. * @returns the buffer
  77293. */
  77294. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77295. return this._multiRenderTarget;
  77296. };
  77297. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77298. /**
  77299. * Gets the number of samples used to render the buffer (anti aliasing).
  77300. */
  77301. get: function () {
  77302. return this._multiRenderTarget.samples;
  77303. },
  77304. /**
  77305. * Sets the number of samples used to render the buffer (anti aliasing).
  77306. */
  77307. set: function (value) {
  77308. this._multiRenderTarget.samples = value;
  77309. },
  77310. enumerable: true,
  77311. configurable: true
  77312. });
  77313. /**
  77314. * Disposes the renderer and frees up associated resources.
  77315. */
  77316. GeometryBufferRenderer.prototype.dispose = function () {
  77317. this.getGBuffer().dispose();
  77318. };
  77319. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77320. var _this = this;
  77321. var engine = this._scene.getEngine();
  77322. var count = this._enablePosition ? 3 : 2;
  77323. 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 });
  77324. if (!this.isSupported) {
  77325. return;
  77326. }
  77327. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77328. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77329. this._multiRenderTarget.refreshRate = 1;
  77330. this._multiRenderTarget.renderParticles = false;
  77331. this._multiRenderTarget.renderList = null;
  77332. // set default depth value to 1.0 (far away)
  77333. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77334. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77335. });
  77336. // Custom render function
  77337. var renderSubMesh = function (subMesh) {
  77338. var mesh = subMesh.getRenderingMesh();
  77339. var scene = _this._scene;
  77340. var engine = scene.getEngine();
  77341. var material = subMesh.getMaterial();
  77342. if (!material) {
  77343. return;
  77344. }
  77345. // Culling
  77346. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77347. // Managing instances
  77348. var batch = mesh._getInstancesRenderList(subMesh._id);
  77349. if (batch.mustReturn) {
  77350. return;
  77351. }
  77352. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77353. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77354. engine.enableEffect(_this._effect);
  77355. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77356. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77357. _this._effect.setMatrix("view", scene.getViewMatrix());
  77358. // Alpha test
  77359. if (material && material.needAlphaTesting()) {
  77360. var alphaTexture = material.getAlphaTestTexture();
  77361. if (alphaTexture) {
  77362. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77363. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77364. }
  77365. }
  77366. // Bones
  77367. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77368. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77369. }
  77370. // Draw
  77371. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77372. }
  77373. };
  77374. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77375. var index;
  77376. if (depthOnlySubMeshes.length) {
  77377. engine.setColorWrite(false);
  77378. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77379. renderSubMesh(depthOnlySubMeshes.data[index]);
  77380. }
  77381. engine.setColorWrite(true);
  77382. }
  77383. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77384. renderSubMesh(opaqueSubMeshes.data[index]);
  77385. }
  77386. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77387. renderSubMesh(alphaTestSubMeshes.data[index]);
  77388. }
  77389. };
  77390. };
  77391. return GeometryBufferRenderer;
  77392. }());
  77393. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77394. })(BABYLON || (BABYLON = {}));
  77395. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77396. var BABYLON;
  77397. (function (BABYLON) {
  77398. /**
  77399. * This groups together the common properties used for image processing either in direct forward pass
  77400. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77401. * or not.
  77402. */
  77403. var ImageProcessingConfiguration = /** @class */ (function () {
  77404. function ImageProcessingConfiguration() {
  77405. /**
  77406. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77407. */
  77408. this.colorCurves = new BABYLON.ColorCurves();
  77409. this._colorCurvesEnabled = false;
  77410. this._colorGradingEnabled = false;
  77411. this._colorGradingWithGreenDepth = true;
  77412. this._colorGradingBGR = true;
  77413. this._exposure = 1.0;
  77414. this._toneMappingEnabled = false;
  77415. this._contrast = 1.0;
  77416. /**
  77417. * Vignette stretch size.
  77418. */
  77419. this.vignetteStretch = 0;
  77420. /**
  77421. * Vignette centre X Offset.
  77422. */
  77423. this.vignetteCentreX = 0;
  77424. /**
  77425. * Vignette centre Y Offset.
  77426. */
  77427. this.vignetteCentreY = 0;
  77428. /**
  77429. * Vignette weight or intensity of the vignette effect.
  77430. */
  77431. this.vignetteWeight = 1.5;
  77432. /**
  77433. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77434. * if vignetteEnabled is set to true.
  77435. */
  77436. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77437. /**
  77438. * Camera field of view used by the Vignette effect.
  77439. */
  77440. this.vignetteCameraFov = 0.5;
  77441. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77442. this._vignetteEnabled = false;
  77443. this._applyByPostProcess = false;
  77444. this._isEnabled = true;
  77445. /**
  77446. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77447. */
  77448. this.onUpdateParameters = new BABYLON.Observable();
  77449. }
  77450. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77451. /**
  77452. * Gets wether the color curves effect is enabled.
  77453. */
  77454. get: function () {
  77455. return this._colorCurvesEnabled;
  77456. },
  77457. /**
  77458. * Sets wether the color curves effect is enabled.
  77459. */
  77460. set: function (value) {
  77461. if (this._colorCurvesEnabled === value) {
  77462. return;
  77463. }
  77464. this._colorCurvesEnabled = value;
  77465. this._updateParameters();
  77466. },
  77467. enumerable: true,
  77468. configurable: true
  77469. });
  77470. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77471. /**
  77472. * Gets wether the color grading effect is enabled.
  77473. */
  77474. get: function () {
  77475. return this._colorGradingEnabled;
  77476. },
  77477. /**
  77478. * Sets wether the color grading effect is enabled.
  77479. */
  77480. set: function (value) {
  77481. if (this._colorGradingEnabled === value) {
  77482. return;
  77483. }
  77484. this._colorGradingEnabled = value;
  77485. this._updateParameters();
  77486. },
  77487. enumerable: true,
  77488. configurable: true
  77489. });
  77490. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77491. /**
  77492. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77493. */
  77494. get: function () {
  77495. return this._colorGradingWithGreenDepth;
  77496. },
  77497. /**
  77498. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77499. */
  77500. set: function (value) {
  77501. if (this._colorGradingWithGreenDepth === value) {
  77502. return;
  77503. }
  77504. this._colorGradingWithGreenDepth = value;
  77505. this._updateParameters();
  77506. },
  77507. enumerable: true,
  77508. configurable: true
  77509. });
  77510. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77511. /**
  77512. * Gets wether the color grading texture contains BGR values.
  77513. */
  77514. get: function () {
  77515. return this._colorGradingBGR;
  77516. },
  77517. /**
  77518. * Sets wether the color grading texture contains BGR values.
  77519. */
  77520. set: function (value) {
  77521. if (this._colorGradingBGR === value) {
  77522. return;
  77523. }
  77524. this._colorGradingBGR = value;
  77525. this._updateParameters();
  77526. },
  77527. enumerable: true,
  77528. configurable: true
  77529. });
  77530. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77531. /**
  77532. * Gets the Exposure used in the effect.
  77533. */
  77534. get: function () {
  77535. return this._exposure;
  77536. },
  77537. /**
  77538. * Sets the Exposure used in the effect.
  77539. */
  77540. set: function (value) {
  77541. if (this._exposure === value) {
  77542. return;
  77543. }
  77544. this._exposure = value;
  77545. this._updateParameters();
  77546. },
  77547. enumerable: true,
  77548. configurable: true
  77549. });
  77550. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77551. /**
  77552. * Gets wether the tone mapping effect is enabled.
  77553. */
  77554. get: function () {
  77555. return this._toneMappingEnabled;
  77556. },
  77557. /**
  77558. * Sets wether the tone mapping effect is enabled.
  77559. */
  77560. set: function (value) {
  77561. if (this._toneMappingEnabled === value) {
  77562. return;
  77563. }
  77564. this._toneMappingEnabled = value;
  77565. this._updateParameters();
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77571. /**
  77572. * Gets the contrast used in the effect.
  77573. */
  77574. get: function () {
  77575. return this._contrast;
  77576. },
  77577. /**
  77578. * Sets the contrast used in the effect.
  77579. */
  77580. set: function (value) {
  77581. if (this._contrast === value) {
  77582. return;
  77583. }
  77584. this._contrast = value;
  77585. this._updateParameters();
  77586. },
  77587. enumerable: true,
  77588. configurable: true
  77589. });
  77590. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77591. /**
  77592. * Gets the vignette blend mode allowing different kind of effect.
  77593. */
  77594. get: function () {
  77595. return this._vignetteBlendMode;
  77596. },
  77597. /**
  77598. * Sets the vignette blend mode allowing different kind of effect.
  77599. */
  77600. set: function (value) {
  77601. if (this._vignetteBlendMode === value) {
  77602. return;
  77603. }
  77604. this._vignetteBlendMode = value;
  77605. this._updateParameters();
  77606. },
  77607. enumerable: true,
  77608. configurable: true
  77609. });
  77610. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77611. /**
  77612. * Gets wether the vignette effect is enabled.
  77613. */
  77614. get: function () {
  77615. return this._vignetteEnabled;
  77616. },
  77617. /**
  77618. * Sets wether the vignette effect is enabled.
  77619. */
  77620. set: function (value) {
  77621. if (this._vignetteEnabled === value) {
  77622. return;
  77623. }
  77624. this._vignetteEnabled = value;
  77625. this._updateParameters();
  77626. },
  77627. enumerable: true,
  77628. configurable: true
  77629. });
  77630. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77631. /**
  77632. * Gets wether the image processing is applied through a post process or not.
  77633. */
  77634. get: function () {
  77635. return this._applyByPostProcess;
  77636. },
  77637. /**
  77638. * Sets wether the image processing is applied through a post process or not.
  77639. */
  77640. set: function (value) {
  77641. if (this._applyByPostProcess === value) {
  77642. return;
  77643. }
  77644. this._applyByPostProcess = value;
  77645. this._updateParameters();
  77646. },
  77647. enumerable: true,
  77648. configurable: true
  77649. });
  77650. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77651. /**
  77652. * Gets wether the image processing is enabled or not.
  77653. */
  77654. get: function () {
  77655. return this._isEnabled;
  77656. },
  77657. /**
  77658. * Sets wether the image processing is enabled or not.
  77659. */
  77660. set: function (value) {
  77661. if (this._isEnabled === value) {
  77662. return;
  77663. }
  77664. this._isEnabled = value;
  77665. this._updateParameters();
  77666. },
  77667. enumerable: true,
  77668. configurable: true
  77669. });
  77670. /**
  77671. * Method called each time the image processing information changes requires to recompile the effect.
  77672. */
  77673. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77674. this.onUpdateParameters.notifyObservers(this);
  77675. };
  77676. ImageProcessingConfiguration.prototype.getClassName = function () {
  77677. return "ImageProcessingConfiguration";
  77678. };
  77679. /**
  77680. * Prepare the list of uniforms associated with the Image Processing effects.
  77681. * @param uniformsList The list of uniforms used in the effect
  77682. * @param defines the list of defines currently in use
  77683. */
  77684. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77685. if (defines.EXPOSURE) {
  77686. uniforms.push("exposureLinear");
  77687. }
  77688. if (defines.CONTRAST) {
  77689. uniforms.push("contrast");
  77690. }
  77691. if (defines.COLORGRADING) {
  77692. uniforms.push("colorTransformSettings");
  77693. }
  77694. if (defines.VIGNETTE) {
  77695. uniforms.push("vInverseScreenSize");
  77696. uniforms.push("vignetteSettings1");
  77697. uniforms.push("vignetteSettings2");
  77698. }
  77699. if (defines.COLORCURVES) {
  77700. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77701. }
  77702. };
  77703. /**
  77704. * Prepare the list of samplers associated with the Image Processing effects.
  77705. * @param uniformsList The list of uniforms used in the effect
  77706. * @param defines the list of defines currently in use
  77707. */
  77708. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77709. if (defines.COLORGRADING) {
  77710. samplersList.push("txColorTransform");
  77711. }
  77712. };
  77713. /**
  77714. * Prepare the list of defines associated to the shader.
  77715. * @param defines the list of defines to complete
  77716. */
  77717. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77718. if (forPostProcess === void 0) { forPostProcess = false; }
  77719. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77720. defines.VIGNETTE = false;
  77721. defines.TONEMAPPING = false;
  77722. defines.CONTRAST = false;
  77723. defines.EXPOSURE = false;
  77724. defines.COLORCURVES = false;
  77725. defines.COLORGRADING = false;
  77726. defines.COLORGRADING3D = false;
  77727. defines.IMAGEPROCESSING = false;
  77728. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77729. return;
  77730. }
  77731. defines.VIGNETTE = this.vignetteEnabled;
  77732. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77733. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77734. defines.TONEMAPPING = this.toneMappingEnabled;
  77735. defines.CONTRAST = (this.contrast !== 1.0);
  77736. defines.EXPOSURE = (this.exposure !== 1.0);
  77737. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77738. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77739. if (defines.COLORGRADING) {
  77740. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77741. }
  77742. else {
  77743. defines.COLORGRADING3D = false;
  77744. }
  77745. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77746. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77747. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77748. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77749. };
  77750. /**
  77751. * Returns true if all the image processing information are ready.
  77752. */
  77753. ImageProcessingConfiguration.prototype.isReady = function () {
  77754. // Color Grading texure can not be none blocking.
  77755. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77756. };
  77757. /**
  77758. * Binds the image processing to the shader.
  77759. * @param effect The effect to bind to
  77760. */
  77761. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77762. if (aspectRatio === void 0) { aspectRatio = 1; }
  77763. // Color Curves
  77764. if (this._colorCurvesEnabled && this.colorCurves) {
  77765. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77766. }
  77767. // Vignette
  77768. if (this._vignetteEnabled) {
  77769. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77770. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77771. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77772. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77773. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77774. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77775. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77776. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77777. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77778. var vignettePower = -2.0 * this.vignetteWeight;
  77779. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77780. }
  77781. // Exposure
  77782. effect.setFloat("exposureLinear", this.exposure);
  77783. // Contrast
  77784. effect.setFloat("contrast", this.contrast);
  77785. // Color transform settings
  77786. if (this.colorGradingTexture) {
  77787. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77788. var textureSize = this.colorGradingTexture.getSize().height;
  77789. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77790. 0.5 / textureSize, // textureOffset
  77791. textureSize, // textureSize
  77792. this.colorGradingTexture.level // weight
  77793. );
  77794. }
  77795. };
  77796. /**
  77797. * Clones the current image processing instance.
  77798. * @return The cloned image processing
  77799. */
  77800. ImageProcessingConfiguration.prototype.clone = function () {
  77801. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77802. };
  77803. /**
  77804. * Serializes the current image processing instance to a json representation.
  77805. * @return a JSON representation
  77806. */
  77807. ImageProcessingConfiguration.prototype.serialize = function () {
  77808. return BABYLON.SerializationHelper.Serialize(this);
  77809. };
  77810. /**
  77811. * Parses the image processing from a json representation.
  77812. * @param source the JSON source to parse
  77813. * @return The parsed image processing
  77814. */
  77815. ImageProcessingConfiguration.Parse = function (source) {
  77816. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77817. };
  77818. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77819. /**
  77820. * Used to apply the vignette as a mix with the pixel color.
  77821. */
  77822. get: function () {
  77823. return this._VIGNETTEMODE_MULTIPLY;
  77824. },
  77825. enumerable: true,
  77826. configurable: true
  77827. });
  77828. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77829. /**
  77830. * Used to apply the vignette as a replacement of the pixel color.
  77831. */
  77832. get: function () {
  77833. return this._VIGNETTEMODE_OPAQUE;
  77834. },
  77835. enumerable: true,
  77836. configurable: true
  77837. });
  77838. // Static constants associated to the image processing.
  77839. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77840. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77841. __decorate([
  77842. BABYLON.serializeAsColorCurves()
  77843. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77844. __decorate([
  77845. BABYLON.serialize()
  77846. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77847. __decorate([
  77848. BABYLON.serializeAsTexture()
  77849. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77850. __decorate([
  77851. BABYLON.serialize()
  77852. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77853. __decorate([
  77854. BABYLON.serialize()
  77855. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77856. __decorate([
  77857. BABYLON.serialize()
  77858. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77859. __decorate([
  77860. BABYLON.serialize()
  77861. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77862. __decorate([
  77863. BABYLON.serialize()
  77864. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77865. __decorate([
  77866. BABYLON.serialize()
  77867. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77868. __decorate([
  77869. BABYLON.serialize()
  77870. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77871. __decorate([
  77872. BABYLON.serialize()
  77873. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77874. __decorate([
  77875. BABYLON.serialize()
  77876. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77877. __decorate([
  77878. BABYLON.serialize()
  77879. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77880. __decorate([
  77881. BABYLON.serializeAsColor4()
  77882. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77883. __decorate([
  77884. BABYLON.serialize()
  77885. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77886. __decorate([
  77887. BABYLON.serialize()
  77888. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77889. __decorate([
  77890. BABYLON.serialize()
  77891. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77892. __decorate([
  77893. BABYLON.serialize()
  77894. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77895. __decorate([
  77896. BABYLON.serialize()
  77897. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77898. return ImageProcessingConfiguration;
  77899. }());
  77900. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77901. })(BABYLON || (BABYLON = {}));
  77902. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77903. var BABYLON;
  77904. (function (BABYLON) {
  77905. /**
  77906. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77907. * It can help converting any input color in a desired output one. This can then be used to create effects
  77908. * from sepia, black and white to sixties or futuristic rendering...
  77909. *
  77910. * The only supported format is currently 3dl.
  77911. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77912. */
  77913. var ColorGradingTexture = /** @class */ (function (_super) {
  77914. __extends(ColorGradingTexture, _super);
  77915. /**
  77916. * Instantiates a ColorGradingTexture from the following parameters.
  77917. *
  77918. * @param url The location of the color gradind data (currently only supporting 3dl)
  77919. * @param scene The scene the texture will be used in
  77920. */
  77921. function ColorGradingTexture(url, scene) {
  77922. var _this = _super.call(this, scene) || this;
  77923. if (!url) {
  77924. return _this;
  77925. }
  77926. _this._engine = scene.getEngine();
  77927. _this._textureMatrix = BABYLON.Matrix.Identity();
  77928. _this.name = url;
  77929. _this.url = url;
  77930. _this.hasAlpha = false;
  77931. _this.isCube = false;
  77932. _this.is3D = _this._engine.webGLVersion > 1;
  77933. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77934. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77935. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77936. _this.anisotropicFilteringLevel = 1;
  77937. _this._texture = _this._getFromCache(url, true);
  77938. if (!_this._texture) {
  77939. if (!scene.useDelayedTextureLoading) {
  77940. _this.loadTexture();
  77941. }
  77942. else {
  77943. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77944. }
  77945. }
  77946. return _this;
  77947. }
  77948. /**
  77949. * Returns the texture matrix used in most of the material.
  77950. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77951. */
  77952. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77953. return this._textureMatrix;
  77954. };
  77955. /**
  77956. * Occurs when the file being loaded is a .3dl LUT file.
  77957. */
  77958. ColorGradingTexture.prototype.load3dlTexture = function () {
  77959. var engine = this._engine;
  77960. var texture;
  77961. if (engine.webGLVersion === 1) {
  77962. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77963. }
  77964. else {
  77965. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77966. }
  77967. this._texture = texture;
  77968. var callback = function (text) {
  77969. if (typeof text !== "string") {
  77970. return;
  77971. }
  77972. var data = null;
  77973. var tempData = null;
  77974. var line;
  77975. var lines = text.split('\n');
  77976. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77977. var maxColor = 0;
  77978. for (var i = 0; i < lines.length; i++) {
  77979. line = lines[i];
  77980. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77981. continue;
  77982. if (line.indexOf('#') === 0)
  77983. continue;
  77984. var words = line.split(" ");
  77985. if (size === 0) {
  77986. // Number of space + one
  77987. size = words.length;
  77988. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77989. tempData = new Float32Array(size * size * size * 4);
  77990. continue;
  77991. }
  77992. if (size != 0) {
  77993. var r = Math.max(parseInt(words[0]), 0);
  77994. var g = Math.max(parseInt(words[1]), 0);
  77995. var b = Math.max(parseInt(words[2]), 0);
  77996. maxColor = Math.max(r, maxColor);
  77997. maxColor = Math.max(g, maxColor);
  77998. maxColor = Math.max(b, maxColor);
  77999. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  78000. if (tempData) {
  78001. tempData[pixelStorageIndex + 0] = r;
  78002. tempData[pixelStorageIndex + 1] = g;
  78003. tempData[pixelStorageIndex + 2] = b;
  78004. }
  78005. pixelIndexSlice++;
  78006. if (pixelIndexSlice % size == 0) {
  78007. pixelIndexH++;
  78008. pixelIndexSlice = 0;
  78009. if (pixelIndexH % size == 0) {
  78010. pixelIndexW++;
  78011. pixelIndexH = 0;
  78012. }
  78013. }
  78014. }
  78015. }
  78016. if (tempData && data) {
  78017. for (var i = 0; i < tempData.length; i++) {
  78018. if (i > 0 && (i + 1) % 4 === 0) {
  78019. data[i] = 255;
  78020. }
  78021. else {
  78022. var value = tempData[i];
  78023. data[i] = (value / maxColor * 255);
  78024. }
  78025. }
  78026. }
  78027. if (texture.is3D) {
  78028. texture.updateSize(size, size, size);
  78029. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78030. }
  78031. else {
  78032. texture.updateSize(size * size, size);
  78033. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78034. }
  78035. };
  78036. var scene = this.getScene();
  78037. if (scene) {
  78038. scene._loadFile(this.url, callback);
  78039. }
  78040. else {
  78041. this._engine._loadFile(this.url, callback);
  78042. }
  78043. return this._texture;
  78044. };
  78045. /**
  78046. * Starts the loading process of the texture.
  78047. */
  78048. ColorGradingTexture.prototype.loadTexture = function () {
  78049. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78050. this.load3dlTexture();
  78051. }
  78052. };
  78053. /**
  78054. * Clones the color gradind texture.
  78055. */
  78056. ColorGradingTexture.prototype.clone = function () {
  78057. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78058. // Base texture
  78059. newTexture.level = this.level;
  78060. return newTexture;
  78061. };
  78062. /**
  78063. * Called during delayed load for textures.
  78064. */
  78065. ColorGradingTexture.prototype.delayLoad = function () {
  78066. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78067. return;
  78068. }
  78069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78070. this._texture = this._getFromCache(this.url, true);
  78071. if (!this._texture) {
  78072. this.loadTexture();
  78073. }
  78074. };
  78075. /**
  78076. * Parses a color grading texture serialized by Babylon.
  78077. * @param parsedTexture The texture information being parsedTexture
  78078. * @param scene The scene to load the texture in
  78079. * @param rootUrl The root url of the data assets to load
  78080. * @return A color gradind texture
  78081. */
  78082. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78083. var texture = null;
  78084. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78085. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78086. texture.name = parsedTexture.name;
  78087. texture.level = parsedTexture.level;
  78088. }
  78089. return texture;
  78090. };
  78091. /**
  78092. * Serializes the LUT texture to json format.
  78093. */
  78094. ColorGradingTexture.prototype.serialize = function () {
  78095. if (!this.name) {
  78096. return null;
  78097. }
  78098. var serializationObject = {};
  78099. serializationObject.name = this.name;
  78100. serializationObject.level = this.level;
  78101. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78102. return serializationObject;
  78103. };
  78104. /**
  78105. * Empty line regex stored for GC.
  78106. */
  78107. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78108. return ColorGradingTexture;
  78109. }(BABYLON.BaseTexture));
  78110. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78111. })(BABYLON || (BABYLON = {}));
  78112. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78113. var BABYLON;
  78114. (function (BABYLON) {
  78115. /**
  78116. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78117. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78118. * 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;
  78119. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78120. */
  78121. var ColorCurves = /** @class */ (function () {
  78122. function ColorCurves() {
  78123. this._dirty = true;
  78124. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78125. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78126. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78127. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78128. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78129. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78130. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78131. this._globalHue = 30;
  78132. this._globalDensity = 0;
  78133. this._globalSaturation = 0;
  78134. this._globalExposure = 0;
  78135. this._highlightsHue = 30;
  78136. this._highlightsDensity = 0;
  78137. this._highlightsSaturation = 0;
  78138. this._highlightsExposure = 0;
  78139. this._midtonesHue = 30;
  78140. this._midtonesDensity = 0;
  78141. this._midtonesSaturation = 0;
  78142. this._midtonesExposure = 0;
  78143. this._shadowsHue = 30;
  78144. this._shadowsDensity = 0;
  78145. this._shadowsSaturation = 0;
  78146. this._shadowsExposure = 0;
  78147. }
  78148. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78149. /**
  78150. * Gets the global Hue value.
  78151. * 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).
  78152. */
  78153. get: function () {
  78154. return this._globalHue;
  78155. },
  78156. /**
  78157. * Sets the global Hue value.
  78158. * 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).
  78159. */
  78160. set: function (value) {
  78161. this._globalHue = value;
  78162. this._dirty = true;
  78163. },
  78164. enumerable: true,
  78165. configurable: true
  78166. });
  78167. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78168. /**
  78169. * Gets the global Density value.
  78170. * 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.
  78171. * Values less than zero provide a filter of opposite hue.
  78172. */
  78173. get: function () {
  78174. return this._globalDensity;
  78175. },
  78176. /**
  78177. * Sets the global Density value.
  78178. * 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.
  78179. * Values less than zero provide a filter of opposite hue.
  78180. */
  78181. set: function (value) {
  78182. this._globalDensity = value;
  78183. this._dirty = true;
  78184. },
  78185. enumerable: true,
  78186. configurable: true
  78187. });
  78188. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78189. /**
  78190. * Gets the global Saturation value.
  78191. * 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.
  78192. */
  78193. get: function () {
  78194. return this._globalSaturation;
  78195. },
  78196. /**
  78197. * Sets the global Saturation value.
  78198. * 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.
  78199. */
  78200. set: function (value) {
  78201. this._globalSaturation = value;
  78202. this._dirty = true;
  78203. },
  78204. enumerable: true,
  78205. configurable: true
  78206. });
  78207. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78208. /**
  78209. * Gets the global Exposure value.
  78210. * 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.
  78211. */
  78212. get: function () {
  78213. return this._globalExposure;
  78214. },
  78215. /**
  78216. * Sets the global Exposure value.
  78217. * 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.
  78218. */
  78219. set: function (value) {
  78220. this._globalExposure = value;
  78221. this._dirty = true;
  78222. },
  78223. enumerable: true,
  78224. configurable: true
  78225. });
  78226. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78227. /**
  78228. * Gets the highlights Hue value.
  78229. * 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).
  78230. */
  78231. get: function () {
  78232. return this._highlightsHue;
  78233. },
  78234. /**
  78235. * Sets the highlights Hue value.
  78236. * 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).
  78237. */
  78238. set: function (value) {
  78239. this._highlightsHue = value;
  78240. this._dirty = true;
  78241. },
  78242. enumerable: true,
  78243. configurable: true
  78244. });
  78245. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78246. /**
  78247. * Gets the highlights Density value.
  78248. * 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.
  78249. * Values less than zero provide a filter of opposite hue.
  78250. */
  78251. get: function () {
  78252. return this._highlightsDensity;
  78253. },
  78254. /**
  78255. * Sets the highlights Density value.
  78256. * 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.
  78257. * Values less than zero provide a filter of opposite hue.
  78258. */
  78259. set: function (value) {
  78260. this._highlightsDensity = value;
  78261. this._dirty = true;
  78262. },
  78263. enumerable: true,
  78264. configurable: true
  78265. });
  78266. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78267. /**
  78268. * Gets the highlights Saturation value.
  78269. * 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.
  78270. */
  78271. get: function () {
  78272. return this._highlightsSaturation;
  78273. },
  78274. /**
  78275. * Sets the highlights Saturation value.
  78276. * 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.
  78277. */
  78278. set: function (value) {
  78279. this._highlightsSaturation = value;
  78280. this._dirty = true;
  78281. },
  78282. enumerable: true,
  78283. configurable: true
  78284. });
  78285. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78286. /**
  78287. * Gets the highlights Exposure value.
  78288. * 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.
  78289. */
  78290. get: function () {
  78291. return this._highlightsExposure;
  78292. },
  78293. /**
  78294. * Sets the highlights Exposure value.
  78295. * 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.
  78296. */
  78297. set: function (value) {
  78298. this._highlightsExposure = value;
  78299. this._dirty = true;
  78300. },
  78301. enumerable: true,
  78302. configurable: true
  78303. });
  78304. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78305. /**
  78306. * Gets the midtones Hue value.
  78307. * 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).
  78308. */
  78309. get: function () {
  78310. return this._midtonesHue;
  78311. },
  78312. /**
  78313. * Sets the midtones Hue value.
  78314. * 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).
  78315. */
  78316. set: function (value) {
  78317. this._midtonesHue = value;
  78318. this._dirty = true;
  78319. },
  78320. enumerable: true,
  78321. configurable: true
  78322. });
  78323. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78324. /**
  78325. * Gets the midtones Density value.
  78326. * 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.
  78327. * Values less than zero provide a filter of opposite hue.
  78328. */
  78329. get: function () {
  78330. return this._midtonesDensity;
  78331. },
  78332. /**
  78333. * Sets the midtones Density value.
  78334. * 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.
  78335. * Values less than zero provide a filter of opposite hue.
  78336. */
  78337. set: function (value) {
  78338. this._midtonesDensity = value;
  78339. this._dirty = true;
  78340. },
  78341. enumerable: true,
  78342. configurable: true
  78343. });
  78344. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78345. /**
  78346. * Gets the midtones Saturation value.
  78347. * 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.
  78348. */
  78349. get: function () {
  78350. return this._midtonesSaturation;
  78351. },
  78352. /**
  78353. * Sets the midtones Saturation value.
  78354. * 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.
  78355. */
  78356. set: function (value) {
  78357. this._midtonesSaturation = value;
  78358. this._dirty = true;
  78359. },
  78360. enumerable: true,
  78361. configurable: true
  78362. });
  78363. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78364. /**
  78365. * Gets the midtones Exposure value.
  78366. * 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.
  78367. */
  78368. get: function () {
  78369. return this._midtonesExposure;
  78370. },
  78371. /**
  78372. * Sets the midtones Exposure value.
  78373. * 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.
  78374. */
  78375. set: function (value) {
  78376. this._midtonesExposure = value;
  78377. this._dirty = true;
  78378. },
  78379. enumerable: true,
  78380. configurable: true
  78381. });
  78382. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78383. /**
  78384. * Gets the shadows Hue value.
  78385. * 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).
  78386. */
  78387. get: function () {
  78388. return this._shadowsHue;
  78389. },
  78390. /**
  78391. * Sets the shadows Hue value.
  78392. * 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).
  78393. */
  78394. set: function (value) {
  78395. this._shadowsHue = value;
  78396. this._dirty = true;
  78397. },
  78398. enumerable: true,
  78399. configurable: true
  78400. });
  78401. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78402. /**
  78403. * Gets the shadows Density value.
  78404. * 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.
  78405. * Values less than zero provide a filter of opposite hue.
  78406. */
  78407. get: function () {
  78408. return this._shadowsDensity;
  78409. },
  78410. /**
  78411. * Sets the shadows Density value.
  78412. * 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.
  78413. * Values less than zero provide a filter of opposite hue.
  78414. */
  78415. set: function (value) {
  78416. this._shadowsDensity = value;
  78417. this._dirty = true;
  78418. },
  78419. enumerable: true,
  78420. configurable: true
  78421. });
  78422. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78423. /**
  78424. * Gets the shadows Saturation value.
  78425. * 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.
  78426. */
  78427. get: function () {
  78428. return this._shadowsSaturation;
  78429. },
  78430. /**
  78431. * Sets the shadows Saturation value.
  78432. * 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.
  78433. */
  78434. set: function (value) {
  78435. this._shadowsSaturation = value;
  78436. this._dirty = true;
  78437. },
  78438. enumerable: true,
  78439. configurable: true
  78440. });
  78441. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78442. /**
  78443. * Gets the shadows Exposure value.
  78444. * 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.
  78445. */
  78446. get: function () {
  78447. return this._shadowsExposure;
  78448. },
  78449. /**
  78450. * Sets the shadows Exposure value.
  78451. * 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.
  78452. */
  78453. set: function (value) {
  78454. this._shadowsExposure = value;
  78455. this._dirty = true;
  78456. },
  78457. enumerable: true,
  78458. configurable: true
  78459. });
  78460. ColorCurves.prototype.getClassName = function () {
  78461. return "ColorCurves";
  78462. };
  78463. /**
  78464. * Binds the color curves to the shader.
  78465. * @param colorCurves The color curve to bind
  78466. * @param effect The effect to bind to
  78467. */
  78468. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78469. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78470. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78471. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78472. if (colorCurves._dirty) {
  78473. colorCurves._dirty = false;
  78474. // Fill in global info.
  78475. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78476. // Compute highlights info.
  78477. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78478. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78479. // Compute midtones info.
  78480. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78481. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78482. // Compute shadows info.
  78483. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78484. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78485. // Compute deltas (neutral is midtones).
  78486. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78487. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78488. }
  78489. if (effect) {
  78490. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78491. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78492. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78493. }
  78494. };
  78495. /**
  78496. * Prepare the list of uniforms associated with the ColorCurves effects.
  78497. * @param uniformsList The list of uniforms used in the effect
  78498. */
  78499. ColorCurves.PrepareUniforms = function (uniformsList) {
  78500. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78501. };
  78502. /**
  78503. * Returns color grading data based on a hue, density, saturation and exposure value.
  78504. * @param filterHue The hue of the color filter.
  78505. * @param filterDensity The density of the color filter.
  78506. * @param saturation The saturation.
  78507. * @param exposure The exposure.
  78508. * @param result The result data container.
  78509. */
  78510. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78511. if (hue == null) {
  78512. return;
  78513. }
  78514. hue = ColorCurves.clamp(hue, 0, 360);
  78515. density = ColorCurves.clamp(density, -100, 100);
  78516. saturation = ColorCurves.clamp(saturation, -100, 100);
  78517. exposure = ColorCurves.clamp(exposure, -100, 100);
  78518. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78519. // so that the maximum filter density is only 50% control. This provides fine control
  78520. // for small values and reasonable range.
  78521. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78522. density *= 0.5;
  78523. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78524. if (density < 0) {
  78525. density *= -1;
  78526. hue = (hue + 180) % 360;
  78527. }
  78528. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78529. result.scaleToRef(2, result);
  78530. result.a = 1 + 0.01 * saturation;
  78531. };
  78532. /**
  78533. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78534. * @param value The input slider value in range [-100,100].
  78535. * @returns Adjusted value.
  78536. */
  78537. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78538. value /= 100;
  78539. var x = Math.abs(value);
  78540. x = Math.pow(x, 2);
  78541. if (value < 0) {
  78542. x *= -1;
  78543. }
  78544. x *= 100;
  78545. return x;
  78546. };
  78547. /**
  78548. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78549. * @param hue The hue (H) input.
  78550. * @param saturation The saturation (S) input.
  78551. * @param brightness The brightness (B) input.
  78552. * @result An RGBA color represented as Vector4.
  78553. */
  78554. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78555. var h = ColorCurves.clamp(hue, 0, 360);
  78556. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78557. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78558. if (s === 0) {
  78559. result.r = v;
  78560. result.g = v;
  78561. result.b = v;
  78562. }
  78563. else {
  78564. // sector 0 to 5
  78565. h /= 60;
  78566. var i = Math.floor(h);
  78567. // fractional part of h
  78568. var f = h - i;
  78569. var p = v * (1 - s);
  78570. var q = v * (1 - s * f);
  78571. var t = v * (1 - s * (1 - f));
  78572. switch (i) {
  78573. case 0:
  78574. result.r = v;
  78575. result.g = t;
  78576. result.b = p;
  78577. break;
  78578. case 1:
  78579. result.r = q;
  78580. result.g = v;
  78581. result.b = p;
  78582. break;
  78583. case 2:
  78584. result.r = p;
  78585. result.g = v;
  78586. result.b = t;
  78587. break;
  78588. case 3:
  78589. result.r = p;
  78590. result.g = q;
  78591. result.b = v;
  78592. break;
  78593. case 4:
  78594. result.r = t;
  78595. result.g = p;
  78596. result.b = v;
  78597. break;
  78598. default: // case 5:
  78599. result.r = v;
  78600. result.g = p;
  78601. result.b = q;
  78602. break;
  78603. }
  78604. }
  78605. result.a = 1;
  78606. };
  78607. /**
  78608. * Returns a value clamped between min and max
  78609. * @param value The value to clamp
  78610. * @param min The minimum of value
  78611. * @param max The maximum of value
  78612. * @returns The clamped value.
  78613. */
  78614. ColorCurves.clamp = function (value, min, max) {
  78615. return Math.min(Math.max(value, min), max);
  78616. };
  78617. /**
  78618. * Clones the current color curve instance.
  78619. * @return The cloned curves
  78620. */
  78621. ColorCurves.prototype.clone = function () {
  78622. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78623. };
  78624. /**
  78625. * Serializes the current color curve instance to a json representation.
  78626. * @return a JSON representation
  78627. */
  78628. ColorCurves.prototype.serialize = function () {
  78629. return BABYLON.SerializationHelper.Serialize(this);
  78630. };
  78631. /**
  78632. * Parses the color curve from a json representation.
  78633. * @param source the JSON source to parse
  78634. * @return The parsed curves
  78635. */
  78636. ColorCurves.Parse = function (source) {
  78637. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78638. };
  78639. __decorate([
  78640. BABYLON.serialize()
  78641. ], ColorCurves.prototype, "_globalHue", void 0);
  78642. __decorate([
  78643. BABYLON.serialize()
  78644. ], ColorCurves.prototype, "_globalDensity", void 0);
  78645. __decorate([
  78646. BABYLON.serialize()
  78647. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78648. __decorate([
  78649. BABYLON.serialize()
  78650. ], ColorCurves.prototype, "_globalExposure", void 0);
  78651. __decorate([
  78652. BABYLON.serialize()
  78653. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78654. __decorate([
  78655. BABYLON.serialize()
  78656. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78657. __decorate([
  78658. BABYLON.serialize()
  78659. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78660. __decorate([
  78661. BABYLON.serialize()
  78662. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78663. __decorate([
  78664. BABYLON.serialize()
  78665. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78666. __decorate([
  78667. BABYLON.serialize()
  78668. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78669. __decorate([
  78670. BABYLON.serialize()
  78671. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78672. __decorate([
  78673. BABYLON.serialize()
  78674. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78675. return ColorCurves;
  78676. }());
  78677. BABYLON.ColorCurves = ColorCurves;
  78678. })(BABYLON || (BABYLON = {}));
  78679. //# sourceMappingURL=babylon.colorCurves.js.map
  78680. var BABYLON;
  78681. (function (BABYLON) {
  78682. var RefractionPostProcess = /** @class */ (function (_super) {
  78683. __extends(RefractionPostProcess, _super);
  78684. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78685. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78686. _this.color = color;
  78687. _this.depth = depth;
  78688. _this.colorLevel = colorLevel;
  78689. _this._ownRefractionTexture = true;
  78690. _this.onActivateObservable.add(function (cam) {
  78691. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78692. });
  78693. _this.onApplyObservable.add(function (effect) {
  78694. effect.setColor3("baseColor", _this.color);
  78695. effect.setFloat("depth", _this.depth);
  78696. effect.setFloat("colorLevel", _this.colorLevel);
  78697. effect.setTexture("refractionSampler", _this._refTexture);
  78698. });
  78699. return _this;
  78700. }
  78701. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78702. /**
  78703. * Gets or sets the refraction texture
  78704. * Please note that you are responsible for disposing the texture if you set it manually
  78705. */
  78706. get: function () {
  78707. return this._refTexture;
  78708. },
  78709. set: function (value) {
  78710. if (this._refTexture && this._ownRefractionTexture) {
  78711. this._refTexture.dispose();
  78712. }
  78713. this._refTexture = value;
  78714. this._ownRefractionTexture = false;
  78715. },
  78716. enumerable: true,
  78717. configurable: true
  78718. });
  78719. // Methods
  78720. RefractionPostProcess.prototype.dispose = function (camera) {
  78721. if (this._refTexture && this._ownRefractionTexture) {
  78722. this._refTexture.dispose();
  78723. this._refTexture = null;
  78724. }
  78725. _super.prototype.dispose.call(this, camera);
  78726. };
  78727. return RefractionPostProcess;
  78728. }(BABYLON.PostProcess));
  78729. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78730. })(BABYLON || (BABYLON = {}));
  78731. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78732. var BABYLON;
  78733. (function (BABYLON) {
  78734. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78735. __extends(BlackAndWhitePostProcess, _super);
  78736. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78737. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78738. _this.degree = 1;
  78739. _this.onApplyObservable.add(function (effect) {
  78740. effect.setFloat("degree", _this.degree);
  78741. });
  78742. return _this;
  78743. }
  78744. return BlackAndWhitePostProcess;
  78745. }(BABYLON.PostProcess));
  78746. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78747. })(BABYLON || (BABYLON = {}));
  78748. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78749. var BABYLON;
  78750. (function (BABYLON) {
  78751. /**
  78752. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78753. * input texture to perform effects such as edge detection or sharpening
  78754. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78755. */
  78756. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78757. __extends(ConvolutionPostProcess, _super);
  78758. /**
  78759. * Creates a new instance ConvolutionPostProcess
  78760. * @param name The name of the effect.
  78761. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78762. * @param options The required width/height ratio to downsize to before computing the render pass.
  78763. * @param camera The camera to apply the render pass to.
  78764. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78765. * @param engine The engine which the post process will be applied. (default: current engine)
  78766. * @param reusable If the post process can be reused on the same frame. (default: false)
  78767. * @param textureType Type of textures used when performing the post process. (default: 0)
  78768. */
  78769. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78770. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78771. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78772. _this.kernel = kernel;
  78773. _this.onApply = function (effect) {
  78774. effect.setFloat2("screenSize", _this.width, _this.height);
  78775. effect.setArray("kernel", _this.kernel);
  78776. };
  78777. return _this;
  78778. }
  78779. // Statics
  78780. /**
  78781. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78782. */
  78783. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78784. /**
  78785. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78786. */
  78787. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78788. /**
  78789. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78790. */
  78791. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78792. /**
  78793. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78794. */
  78795. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78796. /**
  78797. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78798. */
  78799. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78800. /**
  78801. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78802. */
  78803. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78804. return ConvolutionPostProcess;
  78805. }(BABYLON.PostProcess));
  78806. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78807. })(BABYLON || (BABYLON = {}));
  78808. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78809. var BABYLON;
  78810. (function (BABYLON) {
  78811. var FilterPostProcess = /** @class */ (function (_super) {
  78812. __extends(FilterPostProcess, _super);
  78813. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78814. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78815. _this.kernelMatrix = kernelMatrix;
  78816. _this.onApply = function (effect) {
  78817. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78818. };
  78819. return _this;
  78820. }
  78821. return FilterPostProcess;
  78822. }(BABYLON.PostProcess));
  78823. BABYLON.FilterPostProcess = FilterPostProcess;
  78824. })(BABYLON || (BABYLON = {}));
  78825. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78826. var BABYLON;
  78827. (function (BABYLON) {
  78828. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78829. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78830. __extends(VolumetricLightScatteringPostProcess, _super);
  78831. /**
  78832. * @constructor
  78833. * @param {string} name - The post-process name
  78834. * @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)
  78835. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78836. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78837. * @param {number} samples - The post-process quality, default 100
  78838. * @param {number} samplingMode - The post-process filtering mode
  78839. * @param {BABYLON.Engine} engine - The babylon engine
  78840. * @param {boolean} reusable - If the post-process is reusable
  78841. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78842. */
  78843. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78844. if (samples === void 0) { samples = 100; }
  78845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78846. 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;
  78847. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78848. /**
  78849. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78850. */
  78851. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78852. /**
  78853. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78854. */
  78855. _this.useCustomMeshPosition = false;
  78856. /**
  78857. * If the post-process should inverse the light scattering direction
  78858. */
  78859. _this.invert = true;
  78860. /**
  78861. * Array containing the excluded meshes not rendered in the internal pass
  78862. */
  78863. _this.excludedMeshes = new Array();
  78864. /**
  78865. * Controls the overall intensity of the post-process
  78866. */
  78867. _this.exposure = 0.3;
  78868. /**
  78869. * Dissipates each sample's contribution in range [0, 1]
  78870. */
  78871. _this.decay = 0.96815;
  78872. /**
  78873. * Controls the overall intensity of each sample
  78874. */
  78875. _this.weight = 0.58767;
  78876. /**
  78877. * Controls the density of each sample
  78878. */
  78879. _this.density = 0.926;
  78880. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78881. engine = scene.getEngine();
  78882. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78883. // Configure mesh
  78884. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78885. // Configure
  78886. _this._createPass(scene, ratio.passRatio || ratio);
  78887. _this.onActivate = function (camera) {
  78888. if (!_this.isSupported) {
  78889. _this.dispose(camera);
  78890. }
  78891. _this.onActivate = null;
  78892. };
  78893. _this.onApplyObservable.add(function (effect) {
  78894. _this._updateMeshScreenCoordinates(scene);
  78895. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78896. effect.setFloat("exposure", _this.exposure);
  78897. effect.setFloat("decay", _this.decay);
  78898. effect.setFloat("weight", _this.weight);
  78899. effect.setFloat("density", _this.density);
  78900. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78901. });
  78902. return _this;
  78903. }
  78904. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78905. get: function () {
  78906. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78907. return false;
  78908. },
  78909. set: function (useDiffuseColor) {
  78910. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78911. },
  78912. enumerable: true,
  78913. configurable: true
  78914. });
  78915. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78916. return "VolumetricLightScatteringPostProcess";
  78917. };
  78918. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78919. var mesh = subMesh.getMesh();
  78920. // Render this.mesh as default
  78921. if (mesh === this.mesh && mesh.material) {
  78922. return mesh.material.isReady(mesh);
  78923. }
  78924. var defines = [];
  78925. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78926. var material = subMesh.getMaterial();
  78927. // Alpha test
  78928. if (material) {
  78929. if (material.needAlphaTesting()) {
  78930. defines.push("#define ALPHATEST");
  78931. }
  78932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78933. attribs.push(BABYLON.VertexBuffer.UVKind);
  78934. defines.push("#define UV1");
  78935. }
  78936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78937. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78938. defines.push("#define UV2");
  78939. }
  78940. }
  78941. // Bones
  78942. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78943. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78944. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78945. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78946. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78947. }
  78948. else {
  78949. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78950. }
  78951. // Instances
  78952. if (useInstances) {
  78953. defines.push("#define INSTANCES");
  78954. attribs.push("world0");
  78955. attribs.push("world1");
  78956. attribs.push("world2");
  78957. attribs.push("world3");
  78958. }
  78959. // Get correct effect
  78960. var join = defines.join("\n");
  78961. if (this._cachedDefines !== join) {
  78962. this._cachedDefines = join;
  78963. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78964. }
  78965. return this._volumetricLightScatteringPass.isReady();
  78966. };
  78967. /**
  78968. * Sets the new light position for light scattering effect
  78969. * @param {BABYLON.Vector3} The new custom light position
  78970. */
  78971. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78972. this.customMeshPosition = position;
  78973. };
  78974. /**
  78975. * Returns the light position for light scattering effect
  78976. * @return {BABYLON.Vector3} The custom light position
  78977. */
  78978. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78979. return this.customMeshPosition;
  78980. };
  78981. /**
  78982. * Disposes the internal assets and detaches the post-process from the camera
  78983. */
  78984. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78985. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78986. if (rttIndex !== -1) {
  78987. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78988. }
  78989. this._volumetricLightScatteringRTT.dispose();
  78990. _super.prototype.dispose.call(this, camera);
  78991. };
  78992. /**
  78993. * Returns the render target texture used by the post-process
  78994. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78995. */
  78996. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78997. return this._volumetricLightScatteringRTT;
  78998. };
  78999. // Private methods
  79000. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  79001. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  79002. return true;
  79003. }
  79004. return false;
  79005. };
  79006. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  79007. var _this = this;
  79008. var engine = scene.getEngine();
  79009. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79010. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79011. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79012. this._volumetricLightScatteringRTT.renderList = null;
  79013. this._volumetricLightScatteringRTT.renderParticles = false;
  79014. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  79015. var camera = this.getCamera();
  79016. if (camera) {
  79017. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79018. }
  79019. else {
  79020. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79021. }
  79022. // Custom render function for submeshes
  79023. var renderSubMesh = function (subMesh) {
  79024. var mesh = subMesh.getRenderingMesh();
  79025. if (_this._meshExcluded(mesh)) {
  79026. return;
  79027. }
  79028. var material = subMesh.getMaterial();
  79029. if (!material) {
  79030. return;
  79031. }
  79032. var scene = mesh.getScene();
  79033. var engine = scene.getEngine();
  79034. // Culling
  79035. engine.setState(material.backFaceCulling);
  79036. // Managing instances
  79037. var batch = mesh._getInstancesRenderList(subMesh._id);
  79038. if (batch.mustReturn) {
  79039. return;
  79040. }
  79041. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79042. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79043. var effect = _this._volumetricLightScatteringPass;
  79044. if (mesh === _this.mesh) {
  79045. if (subMesh.effect) {
  79046. effect = subMesh.effect;
  79047. }
  79048. else {
  79049. effect = material.getEffect();
  79050. }
  79051. }
  79052. engine.enableEffect(effect);
  79053. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79054. if (mesh === _this.mesh) {
  79055. material.bind(mesh.getWorldMatrix(), mesh);
  79056. }
  79057. else {
  79058. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79059. // Alpha test
  79060. if (material && material.needAlphaTesting()) {
  79061. var alphaTexture = material.getAlphaTestTexture();
  79062. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79063. if (alphaTexture) {
  79064. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79065. }
  79066. }
  79067. // Bones
  79068. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79069. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79070. }
  79071. }
  79072. // Draw
  79073. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79074. }
  79075. };
  79076. // Render target texture callbacks
  79077. var savedSceneClearColor;
  79078. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79079. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79080. savedSceneClearColor = scene.clearColor;
  79081. scene.clearColor = sceneClearColor;
  79082. });
  79083. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79084. scene.clearColor = savedSceneClearColor;
  79085. });
  79086. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79087. var engine = scene.getEngine();
  79088. var index;
  79089. if (depthOnlySubMeshes.length) {
  79090. engine.setColorWrite(false);
  79091. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79092. renderSubMesh(depthOnlySubMeshes.data[index]);
  79093. }
  79094. engine.setColorWrite(true);
  79095. }
  79096. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79097. renderSubMesh(opaqueSubMeshes.data[index]);
  79098. }
  79099. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79100. renderSubMesh(alphaTestSubMeshes.data[index]);
  79101. }
  79102. if (transparentSubMeshes.length) {
  79103. // Sort sub meshes
  79104. for (index = 0; index < transparentSubMeshes.length; index++) {
  79105. var submesh = transparentSubMeshes.data[index];
  79106. var boundingInfo = submesh.getBoundingInfo();
  79107. if (boundingInfo && scene.activeCamera) {
  79108. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79109. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79110. }
  79111. }
  79112. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79113. sortedArray.sort(function (a, b) {
  79114. // Alpha index first
  79115. if (a._alphaIndex > b._alphaIndex) {
  79116. return 1;
  79117. }
  79118. if (a._alphaIndex < b._alphaIndex) {
  79119. return -1;
  79120. }
  79121. // Then distance to camera
  79122. if (a._distanceToCamera < b._distanceToCamera) {
  79123. return 1;
  79124. }
  79125. if (a._distanceToCamera > b._distanceToCamera) {
  79126. return -1;
  79127. }
  79128. return 0;
  79129. });
  79130. // Render sub meshes
  79131. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79132. for (index = 0; index < sortedArray.length; index++) {
  79133. renderSubMesh(sortedArray[index]);
  79134. }
  79135. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79136. }
  79137. };
  79138. };
  79139. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79140. var transform = scene.getTransformMatrix();
  79141. var meshPosition;
  79142. if (this.useCustomMeshPosition) {
  79143. meshPosition = this.customMeshPosition;
  79144. }
  79145. else if (this.attachedNode) {
  79146. meshPosition = this.attachedNode.position;
  79147. }
  79148. else {
  79149. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79150. }
  79151. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79152. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79153. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79154. if (this.invert)
  79155. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79156. };
  79157. // Static methods
  79158. /**
  79159. * Creates a default mesh for the Volumeric Light Scattering post-process
  79160. * @param {string} The mesh name
  79161. * @param {BABYLON.Scene} The scene where to create the mesh
  79162. * @return {BABYLON.Mesh} the default mesh
  79163. */
  79164. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79165. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79166. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79167. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79168. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79169. mesh.material = material;
  79170. return mesh;
  79171. };
  79172. __decorate([
  79173. BABYLON.serializeAsVector3()
  79174. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79175. __decorate([
  79176. BABYLON.serialize()
  79177. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79178. __decorate([
  79179. BABYLON.serialize()
  79180. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79181. __decorate([
  79182. BABYLON.serializeAsMeshReference()
  79183. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79184. __decorate([
  79185. BABYLON.serialize()
  79186. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79187. __decorate([
  79188. BABYLON.serialize()
  79189. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79190. __decorate([
  79191. BABYLON.serialize()
  79192. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79193. __decorate([
  79194. BABYLON.serialize()
  79195. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79196. __decorate([
  79197. BABYLON.serialize()
  79198. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79199. return VolumetricLightScatteringPostProcess;
  79200. }(BABYLON.PostProcess));
  79201. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79202. })(BABYLON || (BABYLON = {}));
  79203. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79204. //
  79205. // This post-process allows the modification of rendered colors by using
  79206. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79207. //
  79208. // The object needs to be provided an url to a texture containing the color
  79209. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79210. // Use an image editing software to tweak the LUT to match your needs.
  79211. //
  79212. // For an example of a color LUT, see here:
  79213. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79214. // For explanations on color grading, see here:
  79215. // http://udn.epicgames.com/Three/ColorGrading.html
  79216. //
  79217. var BABYLON;
  79218. (function (BABYLON) {
  79219. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79220. __extends(ColorCorrectionPostProcess, _super);
  79221. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79222. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79223. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79224. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79225. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79226. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79227. _this.onApply = function (effect) {
  79228. effect.setTexture("colorTable", _this._colorTableTexture);
  79229. };
  79230. return _this;
  79231. }
  79232. return ColorCorrectionPostProcess;
  79233. }(BABYLON.PostProcess));
  79234. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79235. })(BABYLON || (BABYLON = {}));
  79236. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79237. var BABYLON;
  79238. (function (BABYLON) {
  79239. /** Defines operator used for tonemapping */
  79240. var TonemappingOperator;
  79241. (function (TonemappingOperator) {
  79242. /** Hable */
  79243. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79244. /** Reinhard */
  79245. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79246. /** HejiDawson */
  79247. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79248. /** Photographic */
  79249. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79250. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79251. ;
  79252. /**
  79253. * Defines a post process to apply tone mapping
  79254. */
  79255. var TonemapPostProcess = /** @class */ (function (_super) {
  79256. __extends(TonemapPostProcess, _super);
  79257. /**
  79258. * Creates a new TonemapPostProcess
  79259. * @param name defines the name of the postprocess
  79260. * @param _operator defines the operator to use
  79261. * @param exposureAdjustment defines the required exposure adjustement
  79262. * @param camera defines the camera to use (can be null)
  79263. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79264. * @param engine defines the hosting engine (can be ignore if camera is set)
  79265. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79266. */
  79267. function TonemapPostProcess(name, _operator,
  79268. /** Defines the required exposure adjustement */
  79269. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79271. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79272. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79273. _this._operator = _operator;
  79274. _this.exposureAdjustment = exposureAdjustment;
  79275. var defines = "#define ";
  79276. if (_this._operator === TonemappingOperator.Hable)
  79277. defines += "HABLE_TONEMAPPING";
  79278. else if (_this._operator === TonemappingOperator.Reinhard)
  79279. defines += "REINHARD_TONEMAPPING";
  79280. else if (_this._operator === TonemappingOperator.HejiDawson)
  79281. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79282. else if (_this._operator === TonemappingOperator.Photographic)
  79283. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79284. //sadly a second call to create the effect.
  79285. _this.updateEffect(defines);
  79286. _this.onApply = function (effect) {
  79287. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79288. };
  79289. return _this;
  79290. }
  79291. return TonemapPostProcess;
  79292. }(BABYLON.PostProcess));
  79293. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79294. })(BABYLON || (BABYLON = {}));
  79295. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79296. var BABYLON;
  79297. (function (BABYLON) {
  79298. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79299. __extends(DisplayPassPostProcess, _super);
  79300. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79301. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79302. }
  79303. return DisplayPassPostProcess;
  79304. }(BABYLON.PostProcess));
  79305. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79306. })(BABYLON || (BABYLON = {}));
  79307. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79308. var BABYLON;
  79309. (function (BABYLON) {
  79310. var HighlightsPostProcess = /** @class */ (function (_super) {
  79311. __extends(HighlightsPostProcess, _super);
  79312. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79313. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79314. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79315. }
  79316. return HighlightsPostProcess;
  79317. }(BABYLON.PostProcess));
  79318. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79319. })(BABYLON || (BABYLON = {}));
  79320. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79321. var BABYLON;
  79322. (function (BABYLON) {
  79323. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79324. __extends(ImageProcessingPostProcess, _super);
  79325. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79326. if (camera === void 0) { camera = null; }
  79327. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79328. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79329. _this._fromLinearSpace = true;
  79330. /**
  79331. * Defines cache preventing GC.
  79332. */
  79333. _this._defines = {
  79334. IMAGEPROCESSING: false,
  79335. VIGNETTE: false,
  79336. VIGNETTEBLENDMODEMULTIPLY: false,
  79337. VIGNETTEBLENDMODEOPAQUE: false,
  79338. TONEMAPPING: false,
  79339. CONTRAST: false,
  79340. COLORCURVES: false,
  79341. COLORGRADING: false,
  79342. COLORGRADING3D: false,
  79343. FROMLINEARSPACE: false,
  79344. SAMPLER3DGREENDEPTH: false,
  79345. SAMPLER3DBGRMAP: false,
  79346. IMAGEPROCESSINGPOSTPROCESS: false,
  79347. EXPOSURE: false,
  79348. };
  79349. // Setup the configuration as forced by the constructor. This would then not force the
  79350. // scene materials output in linear space and let untouched the default forward pass.
  79351. if (imageProcessingConfiguration) {
  79352. imageProcessingConfiguration.applyByPostProcess = true;
  79353. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79354. // This will cause the shader to be compiled
  79355. _this.fromLinearSpace = false;
  79356. }
  79357. // Setup the default processing configuration to the scene.
  79358. else {
  79359. _this._attachImageProcessingConfiguration(null, true);
  79360. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79361. }
  79362. _this.onApply = function (effect) {
  79363. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79364. };
  79365. return _this;
  79366. }
  79367. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79368. /**
  79369. * Gets the image processing configuration used either in this material.
  79370. */
  79371. get: function () {
  79372. return this._imageProcessingConfiguration;
  79373. },
  79374. /**
  79375. * Sets the Default image processing configuration used either in the this material.
  79376. *
  79377. * If sets to null, the scene one is in use.
  79378. */
  79379. set: function (value) {
  79380. this._attachImageProcessingConfiguration(value);
  79381. },
  79382. enumerable: true,
  79383. configurable: true
  79384. });
  79385. /**
  79386. * Attaches a new image processing configuration to the PBR Material.
  79387. * @param configuration
  79388. */
  79389. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79390. var _this = this;
  79391. if (doNotBuild === void 0) { doNotBuild = false; }
  79392. if (configuration === this._imageProcessingConfiguration) {
  79393. return;
  79394. }
  79395. // Detaches observer.
  79396. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79397. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79398. }
  79399. // Pick the scene configuration if needed.
  79400. if (!configuration) {
  79401. var scene = null;
  79402. var engine = this.getEngine();
  79403. var camera = this.getCamera();
  79404. if (camera) {
  79405. scene = camera.getScene();
  79406. }
  79407. else if (engine && engine.scenes) {
  79408. var scenes = engine.scenes;
  79409. scene = scenes[scenes.length - 1];
  79410. }
  79411. else {
  79412. scene = BABYLON.Engine.LastCreatedScene;
  79413. }
  79414. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79415. }
  79416. else {
  79417. this._imageProcessingConfiguration = configuration;
  79418. }
  79419. // Attaches observer.
  79420. if (this._imageProcessingConfiguration) {
  79421. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79422. _this._updateParameters();
  79423. });
  79424. }
  79425. // Ensure the effect will be rebuilt.
  79426. if (!doNotBuild) {
  79427. this._updateParameters();
  79428. }
  79429. };
  79430. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79431. /**
  79432. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79433. */
  79434. get: function () {
  79435. return this.imageProcessingConfiguration.colorCurves;
  79436. },
  79437. /**
  79438. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79439. */
  79440. set: function (value) {
  79441. this.imageProcessingConfiguration.colorCurves = value;
  79442. },
  79443. enumerable: true,
  79444. configurable: true
  79445. });
  79446. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79447. /**
  79448. * Gets wether the color curves effect is enabled.
  79449. */
  79450. get: function () {
  79451. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79452. },
  79453. /**
  79454. * Sets wether the color curves effect is enabled.
  79455. */
  79456. set: function (value) {
  79457. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79458. },
  79459. enumerable: true,
  79460. configurable: true
  79461. });
  79462. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79463. /**
  79464. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79465. */
  79466. get: function () {
  79467. return this.imageProcessingConfiguration.colorGradingTexture;
  79468. },
  79469. /**
  79470. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79471. */
  79472. set: function (value) {
  79473. this.imageProcessingConfiguration.colorGradingTexture = value;
  79474. },
  79475. enumerable: true,
  79476. configurable: true
  79477. });
  79478. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79479. /**
  79480. * Gets wether the color grading effect is enabled.
  79481. */
  79482. get: function () {
  79483. return this.imageProcessingConfiguration.colorGradingEnabled;
  79484. },
  79485. /**
  79486. * Gets wether the color grading effect is enabled.
  79487. */
  79488. set: function (value) {
  79489. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79490. },
  79491. enumerable: true,
  79492. configurable: true
  79493. });
  79494. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79495. /**
  79496. * Gets exposure used in the effect.
  79497. */
  79498. get: function () {
  79499. return this.imageProcessingConfiguration.exposure;
  79500. },
  79501. /**
  79502. * Sets exposure used in the effect.
  79503. */
  79504. set: function (value) {
  79505. this.imageProcessingConfiguration.exposure = value;
  79506. },
  79507. enumerable: true,
  79508. configurable: true
  79509. });
  79510. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79511. /**
  79512. * Gets wether tonemapping is enabled or not.
  79513. */
  79514. get: function () {
  79515. return this._imageProcessingConfiguration.toneMappingEnabled;
  79516. },
  79517. /**
  79518. * Sets wether tonemapping is enabled or not
  79519. */
  79520. set: function (value) {
  79521. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79522. },
  79523. enumerable: true,
  79524. configurable: true
  79525. });
  79526. ;
  79527. ;
  79528. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79529. /**
  79530. * Gets contrast used in the effect.
  79531. */
  79532. get: function () {
  79533. return this.imageProcessingConfiguration.contrast;
  79534. },
  79535. /**
  79536. * Sets contrast used in the effect.
  79537. */
  79538. set: function (value) {
  79539. this.imageProcessingConfiguration.contrast = value;
  79540. },
  79541. enumerable: true,
  79542. configurable: true
  79543. });
  79544. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79545. /**
  79546. * Gets Vignette stretch size.
  79547. */
  79548. get: function () {
  79549. return this.imageProcessingConfiguration.vignetteStretch;
  79550. },
  79551. /**
  79552. * Sets Vignette stretch size.
  79553. */
  79554. set: function (value) {
  79555. this.imageProcessingConfiguration.vignetteStretch = value;
  79556. },
  79557. enumerable: true,
  79558. configurable: true
  79559. });
  79560. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79561. /**
  79562. * Gets Vignette centre X Offset.
  79563. */
  79564. get: function () {
  79565. return this.imageProcessingConfiguration.vignetteCentreX;
  79566. },
  79567. /**
  79568. * Sets Vignette centre X Offset.
  79569. */
  79570. set: function (value) {
  79571. this.imageProcessingConfiguration.vignetteCentreX = value;
  79572. },
  79573. enumerable: true,
  79574. configurable: true
  79575. });
  79576. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79577. /**
  79578. * Gets Vignette centre Y Offset.
  79579. */
  79580. get: function () {
  79581. return this.imageProcessingConfiguration.vignetteCentreY;
  79582. },
  79583. /**
  79584. * Sets Vignette centre Y Offset.
  79585. */
  79586. set: function (value) {
  79587. this.imageProcessingConfiguration.vignetteCentreY = value;
  79588. },
  79589. enumerable: true,
  79590. configurable: true
  79591. });
  79592. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79593. /**
  79594. * Gets Vignette weight or intensity of the vignette effect.
  79595. */
  79596. get: function () {
  79597. return this.imageProcessingConfiguration.vignetteWeight;
  79598. },
  79599. /**
  79600. * Sets Vignette weight or intensity of the vignette effect.
  79601. */
  79602. set: function (value) {
  79603. this.imageProcessingConfiguration.vignetteWeight = value;
  79604. },
  79605. enumerable: true,
  79606. configurable: true
  79607. });
  79608. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79609. /**
  79610. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79611. * if vignetteEnabled is set to true.
  79612. */
  79613. get: function () {
  79614. return this.imageProcessingConfiguration.vignetteColor;
  79615. },
  79616. /**
  79617. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79618. * if vignetteEnabled is set to true.
  79619. */
  79620. set: function (value) {
  79621. this.imageProcessingConfiguration.vignetteColor = value;
  79622. },
  79623. enumerable: true,
  79624. configurable: true
  79625. });
  79626. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79627. /**
  79628. * Gets Camera field of view used by the Vignette effect.
  79629. */
  79630. get: function () {
  79631. return this.imageProcessingConfiguration.vignetteCameraFov;
  79632. },
  79633. /**
  79634. * Sets Camera field of view used by the Vignette effect.
  79635. */
  79636. set: function (value) {
  79637. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79638. },
  79639. enumerable: true,
  79640. configurable: true
  79641. });
  79642. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79643. /**
  79644. * Gets the vignette blend mode allowing different kind of effect.
  79645. */
  79646. get: function () {
  79647. return this.imageProcessingConfiguration.vignetteBlendMode;
  79648. },
  79649. /**
  79650. * Sets the vignette blend mode allowing different kind of effect.
  79651. */
  79652. set: function (value) {
  79653. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79654. },
  79655. enumerable: true,
  79656. configurable: true
  79657. });
  79658. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79659. /**
  79660. * Gets wether the vignette effect is enabled.
  79661. */
  79662. get: function () {
  79663. return this.imageProcessingConfiguration.vignetteEnabled;
  79664. },
  79665. /**
  79666. * Sets wether the vignette effect is enabled.
  79667. */
  79668. set: function (value) {
  79669. this.imageProcessingConfiguration.vignetteEnabled = value;
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79675. /**
  79676. * Gets wether the input of the processing is in Gamma or Linear Space.
  79677. */
  79678. get: function () {
  79679. return this._fromLinearSpace;
  79680. },
  79681. /**
  79682. * Sets wether the input of the processing is in Gamma or Linear Space.
  79683. */
  79684. set: function (value) {
  79685. if (this._fromLinearSpace === value) {
  79686. return;
  79687. }
  79688. this._fromLinearSpace = value;
  79689. this._updateParameters();
  79690. },
  79691. enumerable: true,
  79692. configurable: true
  79693. });
  79694. ImageProcessingPostProcess.prototype.getClassName = function () {
  79695. return "ImageProcessingPostProcess";
  79696. };
  79697. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79698. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79699. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79700. var defines = "";
  79701. for (var define in this._defines) {
  79702. if (this._defines[define]) {
  79703. defines += "#define " + define + ";\r\n";
  79704. }
  79705. }
  79706. var samplers = ["textureSampler"];
  79707. var uniforms = ["scale"];
  79708. if (BABYLON.ImageProcessingConfiguration) {
  79709. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79710. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79711. }
  79712. this.updateEffect(defines, uniforms, samplers);
  79713. };
  79714. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79715. _super.prototype.dispose.call(this, camera);
  79716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79718. }
  79719. if (this._imageProcessingConfiguration) {
  79720. this.imageProcessingConfiguration.applyByPostProcess = false;
  79721. }
  79722. };
  79723. __decorate([
  79724. BABYLON.serialize()
  79725. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79726. return ImageProcessingPostProcess;
  79727. }(BABYLON.PostProcess));
  79728. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79729. })(BABYLON || (BABYLON = {}));
  79730. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79731. var BABYLON;
  79732. (function (BABYLON) {
  79733. /**
  79734. * Class used to store bone information
  79735. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79736. */
  79737. var Bone = /** @class */ (function (_super) {
  79738. __extends(Bone, _super);
  79739. /**
  79740. * Create a new bone
  79741. * @param name defines the bone name
  79742. * @param skeleton defines the parent skeleton
  79743. * @param parentBone defines the parent (can be null if the bone is the root)
  79744. * @param localMatrix defines the local matrix
  79745. * @param restPose defines the rest pose matrix
  79746. * @param baseMatrix defines the base matrix
  79747. * @param index defines index of the bone in the hiearchy
  79748. */
  79749. function Bone(
  79750. /**
  79751. * defines the bone name
  79752. */
  79753. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79754. if (parentBone === void 0) { parentBone = null; }
  79755. if (localMatrix === void 0) { localMatrix = null; }
  79756. if (restPose === void 0) { restPose = null; }
  79757. if (baseMatrix === void 0) { baseMatrix = null; }
  79758. if (index === void 0) { index = null; }
  79759. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79760. _this.name = name;
  79761. /**
  79762. * Gets the list of child bones
  79763. */
  79764. _this.children = new Array();
  79765. /** Gets the animations associated with this bone */
  79766. _this.animations = new Array();
  79767. /**
  79768. * @hidden Internal only
  79769. * Set this value to map this bone to a different index in the transform matrices
  79770. * Set this value to -1 to exclude the bone from the transform matrices
  79771. */
  79772. _this._index = null;
  79773. _this._absoluteTransform = new BABYLON.Matrix();
  79774. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79775. _this._scalingDeterminant = 1;
  79776. _this._worldTransform = new BABYLON.Matrix();
  79777. _this._needToDecompose = true;
  79778. _this._needToCompose = false;
  79779. _this._skeleton = skeleton;
  79780. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79781. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79782. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79783. _this._index = index;
  79784. skeleton.bones.push(_this);
  79785. _this.setParent(parentBone, false);
  79786. if (baseMatrix || localMatrix) {
  79787. _this._updateDifferenceMatrix();
  79788. }
  79789. return _this;
  79790. }
  79791. Object.defineProperty(Bone.prototype, "_matrix", {
  79792. /** @hidden */
  79793. get: function () {
  79794. this._compose();
  79795. return this._localMatrix;
  79796. },
  79797. /** @hidden */
  79798. set: function (value) {
  79799. this._localMatrix.copyFrom(value);
  79800. this._needToDecompose = true;
  79801. },
  79802. enumerable: true,
  79803. configurable: true
  79804. });
  79805. // Members
  79806. /**
  79807. * Gets the parent skeleton
  79808. * @returns a skeleton
  79809. */
  79810. Bone.prototype.getSkeleton = function () {
  79811. return this._skeleton;
  79812. };
  79813. /**
  79814. * Gets parent bone
  79815. * @returns a bone or null if the bone is the root of the bone hierarchy
  79816. */
  79817. Bone.prototype.getParent = function () {
  79818. return this._parent;
  79819. };
  79820. /**
  79821. * Sets the parent bone
  79822. * @param parent defines the parent (can be null if the bone is the root)
  79823. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79824. */
  79825. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79826. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79827. if (this._parent === parent) {
  79828. return;
  79829. }
  79830. if (this._parent) {
  79831. var index = this._parent.children.indexOf(this);
  79832. if (index !== -1) {
  79833. this._parent.children.splice(index, 1);
  79834. }
  79835. }
  79836. this._parent = parent;
  79837. if (this._parent) {
  79838. this._parent.children.push(this);
  79839. }
  79840. if (updateDifferenceMatrix) {
  79841. this._updateDifferenceMatrix();
  79842. }
  79843. this.markAsDirty();
  79844. };
  79845. /**
  79846. * Gets the local matrix
  79847. * @returns a matrix
  79848. */
  79849. Bone.prototype.getLocalMatrix = function () {
  79850. this._compose();
  79851. return this._localMatrix;
  79852. };
  79853. /**
  79854. * Gets the base matrix (initial matrix which remains unchanged)
  79855. * @returns a matrix
  79856. */
  79857. Bone.prototype.getBaseMatrix = function () {
  79858. return this._baseMatrix;
  79859. };
  79860. /**
  79861. * Gets the rest pose matrix
  79862. * @returns a matrix
  79863. */
  79864. Bone.prototype.getRestPose = function () {
  79865. return this._restPose;
  79866. };
  79867. /**
  79868. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79869. */
  79870. Bone.prototype.getWorldMatrix = function () {
  79871. return this._worldTransform;
  79872. };
  79873. /**
  79874. * Sets the local matrix to rest pose matrix
  79875. */
  79876. Bone.prototype.returnToRest = function () {
  79877. this.updateMatrix(this._restPose.clone());
  79878. };
  79879. /**
  79880. * Gets the inverse of the absolute transform matrix.
  79881. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79882. * @returns a matrix
  79883. */
  79884. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79885. return this._invertedAbsoluteTransform;
  79886. };
  79887. /**
  79888. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79889. * @returns a matrix
  79890. */
  79891. Bone.prototype.getAbsoluteTransform = function () {
  79892. return this._absoluteTransform;
  79893. };
  79894. Object.defineProperty(Bone.prototype, "position", {
  79895. // Properties (matches AbstractMesh properties)
  79896. /** Gets or sets current position (in local space) */
  79897. get: function () {
  79898. this._decompose();
  79899. return this._localPosition;
  79900. },
  79901. set: function (newPosition) {
  79902. this._decompose();
  79903. this._localPosition.copyFrom(newPosition);
  79904. this._markAsDirtyAndCompose();
  79905. },
  79906. enumerable: true,
  79907. configurable: true
  79908. });
  79909. Object.defineProperty(Bone.prototype, "rotation", {
  79910. /** Gets or sets current rotation (in local space) */
  79911. get: function () {
  79912. return this.getRotation();
  79913. },
  79914. set: function (newRotation) {
  79915. this.setRotation(newRotation);
  79916. },
  79917. enumerable: true,
  79918. configurable: true
  79919. });
  79920. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79921. /** Gets or sets current rotation quaternion (in local space) */
  79922. get: function () {
  79923. this._decompose();
  79924. return this._localRotation;
  79925. },
  79926. set: function (newRotation) {
  79927. this.setRotationQuaternion(newRotation);
  79928. },
  79929. enumerable: true,
  79930. configurable: true
  79931. });
  79932. Object.defineProperty(Bone.prototype, "scaling", {
  79933. /** Gets or sets current scaling (in local space) */
  79934. get: function () {
  79935. return this.getScale();
  79936. },
  79937. set: function (newScaling) {
  79938. this.setScale(newScaling);
  79939. },
  79940. enumerable: true,
  79941. configurable: true
  79942. });
  79943. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79944. /**
  79945. * Gets the animation properties override
  79946. */
  79947. get: function () {
  79948. return this._skeleton.animationPropertiesOverride;
  79949. },
  79950. enumerable: true,
  79951. configurable: true
  79952. });
  79953. // Methods
  79954. Bone.prototype._decompose = function () {
  79955. if (!this._needToDecompose) {
  79956. return;
  79957. }
  79958. this._needToDecompose = false;
  79959. if (!this._localScaling) {
  79960. this._localScaling = BABYLON.Vector3.Zero();
  79961. this._localRotation = BABYLON.Quaternion.Zero();
  79962. this._localPosition = BABYLON.Vector3.Zero();
  79963. }
  79964. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79965. };
  79966. Bone.prototype._compose = function () {
  79967. if (!this._needToCompose) {
  79968. return;
  79969. }
  79970. this._needToCompose = false;
  79971. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79972. };
  79973. /**
  79974. * Update the base and local matrices
  79975. * @param matrix defines the new base or local matrix
  79976. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79977. * @param updateLocalMatrix defines if the local matrix should be updated
  79978. */
  79979. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79980. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79981. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79982. this._baseMatrix.copyFrom(matrix);
  79983. if (updateDifferenceMatrix) {
  79984. this._updateDifferenceMatrix();
  79985. }
  79986. if (updateLocalMatrix) {
  79987. this._localMatrix.copyFrom(matrix);
  79988. this._markAsDirtyAndDecompose();
  79989. }
  79990. else {
  79991. this.markAsDirty();
  79992. }
  79993. };
  79994. /** @hidden */
  79995. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79996. if (updateChildren === void 0) { updateChildren = true; }
  79997. if (!rootMatrix) {
  79998. rootMatrix = this._baseMatrix;
  79999. }
  80000. if (this._parent) {
  80001. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80002. }
  80003. else {
  80004. this._absoluteTransform.copyFrom(rootMatrix);
  80005. }
  80006. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  80007. if (updateChildren) {
  80008. for (var index = 0; index < this.children.length; index++) {
  80009. this.children[index]._updateDifferenceMatrix();
  80010. }
  80011. }
  80012. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  80013. };
  80014. /**
  80015. * Flag the bone as dirty (Forcing it to update everything)
  80016. */
  80017. Bone.prototype.markAsDirty = function () {
  80018. this._currentRenderId++;
  80019. this._childRenderId++;
  80020. this._skeleton._markAsDirty();
  80021. };
  80022. Bone.prototype._markAsDirtyAndCompose = function () {
  80023. this.markAsDirty();
  80024. this._needToCompose = true;
  80025. };
  80026. Bone.prototype._markAsDirtyAndDecompose = function () {
  80027. this.markAsDirty();
  80028. this._needToDecompose = true;
  80029. };
  80030. /**
  80031. * Copy an animation range from another bone
  80032. * @param source defines the source bone
  80033. * @param rangeName defines the range name to copy
  80034. * @param frameOffset defines the frame offset
  80035. * @param rescaleAsRequired defines if rescaling must be applied if required
  80036. * @param skelDimensionsRatio defines the scaling ratio
  80037. * @returns true if operation was successful
  80038. */
  80039. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80040. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80041. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80042. // all animation may be coming from a library skeleton, so may need to create animation
  80043. if (this.animations.length === 0) {
  80044. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80045. this.animations[0].setKeys([]);
  80046. }
  80047. // get animation info / verify there is such a range from the source bone
  80048. var sourceRange = source.animations[0].getRange(rangeName);
  80049. if (!sourceRange) {
  80050. return false;
  80051. }
  80052. var from = sourceRange.from;
  80053. var to = sourceRange.to;
  80054. var sourceKeys = source.animations[0].getKeys();
  80055. // rescaling prep
  80056. var sourceBoneLength = source.length;
  80057. var sourceParent = source.getParent();
  80058. var parent = this.getParent();
  80059. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80060. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80061. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80062. var destKeys = this.animations[0].getKeys();
  80063. // loop vars declaration
  80064. var orig;
  80065. var origTranslation;
  80066. var mat;
  80067. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80068. orig = sourceKeys[key];
  80069. if (orig.frame >= from && orig.frame <= to) {
  80070. if (rescaleAsRequired) {
  80071. mat = orig.value.clone();
  80072. // scale based on parent ratio, when bone has parent
  80073. if (parentScalingReqd) {
  80074. origTranslation = mat.getTranslation();
  80075. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80076. // scale based on skeleton dimension ratio when root bone, and value is passed
  80077. }
  80078. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80079. origTranslation = mat.getTranslation();
  80080. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80081. // use original when root bone, and no data for skelDimensionsRatio
  80082. }
  80083. else {
  80084. mat = orig.value;
  80085. }
  80086. }
  80087. else {
  80088. mat = orig.value;
  80089. }
  80090. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80091. }
  80092. }
  80093. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80094. return true;
  80095. };
  80096. /**
  80097. * Translate the bone in local or world space
  80098. * @param vec The amount to translate the bone
  80099. * @param space The space that the translation is in
  80100. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80101. */
  80102. Bone.prototype.translate = function (vec, space, mesh) {
  80103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80104. var lm = this.getLocalMatrix();
  80105. if (space == BABYLON.Space.LOCAL) {
  80106. lm.m[12] += vec.x;
  80107. lm.m[13] += vec.y;
  80108. lm.m[14] += vec.z;
  80109. }
  80110. else {
  80111. var wm = null;
  80112. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80113. if (mesh) {
  80114. wm = mesh.getWorldMatrix();
  80115. }
  80116. this._skeleton.computeAbsoluteTransforms();
  80117. var tmat = Bone._tmpMats[0];
  80118. var tvec = Bone._tmpVecs[0];
  80119. if (this._parent) {
  80120. if (mesh && wm) {
  80121. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80122. tmat.multiplyToRef(wm, tmat);
  80123. }
  80124. else {
  80125. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80126. }
  80127. }
  80128. tmat.m[12] = 0;
  80129. tmat.m[13] = 0;
  80130. tmat.m[14] = 0;
  80131. tmat.invert();
  80132. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80133. lm.m[12] += tvec.x;
  80134. lm.m[13] += tvec.y;
  80135. lm.m[14] += tvec.z;
  80136. }
  80137. this._markAsDirtyAndDecompose();
  80138. };
  80139. /**
  80140. * Set the postion of the bone in local or world space
  80141. * @param position The position to set the bone
  80142. * @param space The space that the position is in
  80143. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80144. */
  80145. Bone.prototype.setPosition = function (position, space, mesh) {
  80146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80147. var lm = this.getLocalMatrix();
  80148. if (space == BABYLON.Space.LOCAL) {
  80149. lm.m[12] = position.x;
  80150. lm.m[13] = position.y;
  80151. lm.m[14] = position.z;
  80152. }
  80153. else {
  80154. var wm = null;
  80155. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80156. if (mesh) {
  80157. wm = mesh.getWorldMatrix();
  80158. }
  80159. this._skeleton.computeAbsoluteTransforms();
  80160. var tmat = Bone._tmpMats[0];
  80161. var vec = Bone._tmpVecs[0];
  80162. if (this._parent) {
  80163. if (mesh && wm) {
  80164. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80165. tmat.multiplyToRef(wm, tmat);
  80166. }
  80167. else {
  80168. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80169. }
  80170. }
  80171. tmat.invert();
  80172. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80173. lm.m[12] = vec.x;
  80174. lm.m[13] = vec.y;
  80175. lm.m[14] = vec.z;
  80176. }
  80177. this._markAsDirtyAndDecompose();
  80178. };
  80179. /**
  80180. * Set the absolute position of the bone (world space)
  80181. * @param position The position to set the bone
  80182. * @param mesh The mesh that this bone is attached to
  80183. */
  80184. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80185. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80186. };
  80187. /**
  80188. * Scale the bone on the x, y and z axes (in local space)
  80189. * @param x The amount to scale the bone on the x axis
  80190. * @param y The amount to scale the bone on the y axis
  80191. * @param z The amount to scale the bone on the z axis
  80192. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80193. */
  80194. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80195. if (scaleChildren === void 0) { scaleChildren = false; }
  80196. var locMat = this.getLocalMatrix();
  80197. // Apply new scaling on top of current local matrix
  80198. var scaleMat = Bone._tmpMats[0];
  80199. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80200. scaleMat.multiplyToRef(locMat, locMat);
  80201. // Invert scaling matrix and apply the inverse to all children
  80202. scaleMat.invert();
  80203. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80204. var child = _a[_i];
  80205. var cm = child.getLocalMatrix();
  80206. cm.multiplyToRef(scaleMat, cm);
  80207. cm.m[12] *= x;
  80208. cm.m[13] *= y;
  80209. cm.m[14] *= z;
  80210. child._markAsDirtyAndDecompose();
  80211. }
  80212. this._markAsDirtyAndDecompose();
  80213. if (scaleChildren) {
  80214. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80215. var child = _c[_b];
  80216. child.scale(x, y, z, scaleChildren);
  80217. }
  80218. }
  80219. };
  80220. /**
  80221. * Set the bone scaling in local space
  80222. * @param scale defines the scaling vector
  80223. */
  80224. Bone.prototype.setScale = function (scale) {
  80225. this._decompose();
  80226. this._localScaling.copyFrom(scale);
  80227. this._markAsDirtyAndCompose();
  80228. };
  80229. /**
  80230. * Gets the current scaling in local space
  80231. * @returns the current scaling vector
  80232. */
  80233. Bone.prototype.getScale = function () {
  80234. this._decompose();
  80235. return this._localScaling;
  80236. };
  80237. /**
  80238. * Gets the current scaling in local space and stores it in a target vector
  80239. * @param result defines the target vector
  80240. */
  80241. Bone.prototype.getScaleToRef = function (result) {
  80242. this._decompose();
  80243. result.copyFrom(this._localScaling);
  80244. };
  80245. /**
  80246. * Set the yaw, pitch, and roll of the bone in local or world space
  80247. * @param yaw The rotation of the bone on the y axis
  80248. * @param pitch The rotation of the bone on the x axis
  80249. * @param roll The rotation of the bone on the z axis
  80250. * @param space The space that the axes of rotation are in
  80251. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80252. */
  80253. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80255. if (space === BABYLON.Space.LOCAL) {
  80256. var quat = Bone._tmpQuat;
  80257. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80258. this.setRotationQuaternion(quat, space, mesh);
  80259. return;
  80260. }
  80261. var rotMatInv = Bone._tmpMats[0];
  80262. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80263. return;
  80264. }
  80265. var rotMat = Bone._tmpMats[1];
  80266. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80267. rotMatInv.multiplyToRef(rotMat, rotMat);
  80268. this._rotateWithMatrix(rotMat, space, mesh);
  80269. };
  80270. /**
  80271. * Add a rotation to the bone on an axis in local or world space
  80272. * @param axis The axis to rotate the bone on
  80273. * @param amount The amount to rotate the bone
  80274. * @param space The space that the axis is in
  80275. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80276. */
  80277. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80279. var rmat = Bone._tmpMats[0];
  80280. rmat.m[12] = 0;
  80281. rmat.m[13] = 0;
  80282. rmat.m[14] = 0;
  80283. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80284. this._rotateWithMatrix(rmat, space, mesh);
  80285. };
  80286. /**
  80287. * Set the rotation of the bone to a particular axis angle in local or world space
  80288. * @param axis The axis to rotate the bone on
  80289. * @param angle The angle that the bone should be rotated to
  80290. * @param space The space that the axis is in
  80291. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80292. */
  80293. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80294. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80295. if (space === BABYLON.Space.LOCAL) {
  80296. var quat = Bone._tmpQuat;
  80297. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80298. this.setRotationQuaternion(quat, space, mesh);
  80299. return;
  80300. }
  80301. var rotMatInv = Bone._tmpMats[0];
  80302. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80303. return;
  80304. }
  80305. var rotMat = Bone._tmpMats[1];
  80306. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80307. rotMatInv.multiplyToRef(rotMat, rotMat);
  80308. this._rotateWithMatrix(rotMat, space, mesh);
  80309. };
  80310. /**
  80311. * Set the euler rotation of the bone in local of world space
  80312. * @param rotation The euler rotation that the bone should be set to
  80313. * @param space The space that the rotation is in
  80314. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80315. */
  80316. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80318. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80319. };
  80320. /**
  80321. * Set the quaternion rotation of the bone in local of world space
  80322. * @param quat The quaternion rotation that the bone should be set to
  80323. * @param space The space that the rotation is in
  80324. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80325. */
  80326. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80327. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80328. if (space === BABYLON.Space.LOCAL) {
  80329. this._decompose();
  80330. this._localRotation.copyFrom(quat);
  80331. this._markAsDirtyAndCompose();
  80332. return;
  80333. }
  80334. var rotMatInv = Bone._tmpMats[0];
  80335. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80336. return;
  80337. }
  80338. var rotMat = Bone._tmpMats[1];
  80339. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80340. rotMatInv.multiplyToRef(rotMat, rotMat);
  80341. this._rotateWithMatrix(rotMat, space, mesh);
  80342. };
  80343. /**
  80344. * Set the rotation matrix of the bone in local of world space
  80345. * @param rotMat The rotation matrix that the bone should be set to
  80346. * @param space The space that the rotation is in
  80347. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80348. */
  80349. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80351. if (space === BABYLON.Space.LOCAL) {
  80352. var quat = Bone._tmpQuat;
  80353. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80354. this.setRotationQuaternion(quat, space, mesh);
  80355. return;
  80356. }
  80357. var rotMatInv = Bone._tmpMats[0];
  80358. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80359. return;
  80360. }
  80361. var rotMat2 = Bone._tmpMats[1];
  80362. rotMat2.copyFrom(rotMat);
  80363. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80364. this._rotateWithMatrix(rotMat2, space, mesh);
  80365. };
  80366. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80367. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80368. var lmat = this.getLocalMatrix();
  80369. var lx = lmat.m[12];
  80370. var ly = lmat.m[13];
  80371. var lz = lmat.m[14];
  80372. var parent = this.getParent();
  80373. var parentScale = Bone._tmpMats[3];
  80374. var parentScaleInv = Bone._tmpMats[4];
  80375. if (parent && space == BABYLON.Space.WORLD) {
  80376. if (mesh) {
  80377. parentScale.copyFrom(mesh.getWorldMatrix());
  80378. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80379. }
  80380. else {
  80381. parentScale.copyFrom(parent.getAbsoluteTransform());
  80382. }
  80383. parentScaleInv.copyFrom(parentScale);
  80384. parentScaleInv.invert();
  80385. lmat.multiplyToRef(parentScale, lmat);
  80386. lmat.multiplyToRef(rmat, lmat);
  80387. lmat.multiplyToRef(parentScaleInv, lmat);
  80388. }
  80389. else {
  80390. if (space == BABYLON.Space.WORLD && mesh) {
  80391. parentScale.copyFrom(mesh.getWorldMatrix());
  80392. parentScaleInv.copyFrom(parentScale);
  80393. parentScaleInv.invert();
  80394. lmat.multiplyToRef(parentScale, lmat);
  80395. lmat.multiplyToRef(rmat, lmat);
  80396. lmat.multiplyToRef(parentScaleInv, lmat);
  80397. }
  80398. else {
  80399. lmat.multiplyToRef(rmat, lmat);
  80400. }
  80401. }
  80402. lmat.m[12] = lx;
  80403. lmat.m[13] = ly;
  80404. lmat.m[14] = lz;
  80405. this.computeAbsoluteTransforms();
  80406. this._markAsDirtyAndDecompose();
  80407. };
  80408. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80409. var scaleMatrix = Bone._tmpMats[2];
  80410. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80411. if (mesh) {
  80412. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80413. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80414. }
  80415. rotMatInv.invert();
  80416. if (isNaN(rotMatInv.m[0])) {
  80417. // Matrix failed to invert.
  80418. // This can happen if scale is zero for example.
  80419. return false;
  80420. }
  80421. scaleMatrix.m[0] *= this._scalingDeterminant;
  80422. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80423. return true;
  80424. };
  80425. /**
  80426. * Get the position of the bone in local or world space
  80427. * @param space The space that the returned position is in
  80428. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80429. * @returns The position of the bone
  80430. */
  80431. Bone.prototype.getPosition = function (space, mesh) {
  80432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80433. if (mesh === void 0) { mesh = null; }
  80434. var pos = BABYLON.Vector3.Zero();
  80435. this.getPositionToRef(space, mesh, pos);
  80436. return pos;
  80437. };
  80438. /**
  80439. * Copy the position of the bone to a vector3 in local or world space
  80440. * @param space The space that the returned position is in
  80441. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80442. * @param result The vector3 to copy the position to
  80443. */
  80444. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80446. if (space == BABYLON.Space.LOCAL) {
  80447. var lm = this.getLocalMatrix();
  80448. result.x = lm.m[12];
  80449. result.y = lm.m[13];
  80450. result.z = lm.m[14];
  80451. }
  80452. else {
  80453. var wm = null;
  80454. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80455. if (mesh) {
  80456. wm = mesh.getWorldMatrix();
  80457. }
  80458. this._skeleton.computeAbsoluteTransforms();
  80459. var tmat = Bone._tmpMats[0];
  80460. if (mesh && wm) {
  80461. tmat.copyFrom(this.getAbsoluteTransform());
  80462. tmat.multiplyToRef(wm, tmat);
  80463. }
  80464. else {
  80465. tmat = this.getAbsoluteTransform();
  80466. }
  80467. result.x = tmat.m[12];
  80468. result.y = tmat.m[13];
  80469. result.z = tmat.m[14];
  80470. }
  80471. };
  80472. /**
  80473. * Get the absolute position of the bone (world space)
  80474. * @param mesh The mesh that this bone is attached to
  80475. * @returns The absolute position of the bone
  80476. */
  80477. Bone.prototype.getAbsolutePosition = function (mesh) {
  80478. if (mesh === void 0) { mesh = null; }
  80479. var pos = BABYLON.Vector3.Zero();
  80480. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80481. return pos;
  80482. };
  80483. /**
  80484. * Copy the absolute position of the bone (world space) to the result param
  80485. * @param mesh The mesh that this bone is attached to
  80486. * @param result The vector3 to copy the absolute position to
  80487. */
  80488. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80489. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80490. };
  80491. /**
  80492. * Compute the absolute transforms of this bone and its children
  80493. */
  80494. Bone.prototype.computeAbsoluteTransforms = function () {
  80495. this._compose();
  80496. if (this._parent) {
  80497. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80498. }
  80499. else {
  80500. this._absoluteTransform.copyFrom(this._localMatrix);
  80501. var poseMatrix = this._skeleton.getPoseMatrix();
  80502. if (poseMatrix) {
  80503. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80504. }
  80505. }
  80506. var children = this.children;
  80507. var len = children.length;
  80508. for (var i = 0; i < len; i++) {
  80509. children[i].computeAbsoluteTransforms();
  80510. }
  80511. };
  80512. /**
  80513. * Get the world direction from an axis that is in the local space of the bone
  80514. * @param localAxis The local direction that is used to compute the world direction
  80515. * @param mesh The mesh that this bone is attached to
  80516. * @returns The world direction
  80517. */
  80518. Bone.prototype.getDirection = function (localAxis, mesh) {
  80519. if (mesh === void 0) { mesh = null; }
  80520. var result = BABYLON.Vector3.Zero();
  80521. this.getDirectionToRef(localAxis, mesh, result);
  80522. return result;
  80523. };
  80524. /**
  80525. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80526. * @param localAxis The local direction that is used to compute the world direction
  80527. * @param mesh The mesh that this bone is attached to
  80528. * @param result The vector3 that the world direction will be copied to
  80529. */
  80530. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80531. if (mesh === void 0) { mesh = null; }
  80532. var wm = null;
  80533. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80534. if (mesh) {
  80535. wm = mesh.getWorldMatrix();
  80536. }
  80537. this._skeleton.computeAbsoluteTransforms();
  80538. var mat = Bone._tmpMats[0];
  80539. mat.copyFrom(this.getAbsoluteTransform());
  80540. if (mesh && wm) {
  80541. mat.multiplyToRef(wm, mat);
  80542. }
  80543. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80544. result.normalize();
  80545. };
  80546. /**
  80547. * Get the euler rotation of the bone in local or world space
  80548. * @param space The space that the rotation should be in
  80549. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80550. * @returns The euler rotation
  80551. */
  80552. Bone.prototype.getRotation = function (space, mesh) {
  80553. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80554. if (mesh === void 0) { mesh = null; }
  80555. var result = BABYLON.Vector3.Zero();
  80556. this.getRotationToRef(space, mesh, result);
  80557. return result;
  80558. };
  80559. /**
  80560. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80561. * @param space The space that the rotation should be in
  80562. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80563. * @param result The vector3 that the rotation should be copied to
  80564. */
  80565. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80566. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80567. if (mesh === void 0) { mesh = null; }
  80568. var quat = Bone._tmpQuat;
  80569. this.getRotationQuaternionToRef(space, mesh, quat);
  80570. quat.toEulerAnglesToRef(result);
  80571. };
  80572. /**
  80573. * Get the quaternion rotation of the bone in either local or world space
  80574. * @param space The space that the rotation should be in
  80575. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80576. * @returns The quaternion rotation
  80577. */
  80578. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80580. if (mesh === void 0) { mesh = null; }
  80581. var result = BABYLON.Quaternion.Identity();
  80582. this.getRotationQuaternionToRef(space, mesh, result);
  80583. return result;
  80584. };
  80585. /**
  80586. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80587. * @param space The space that the rotation should be in
  80588. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80589. * @param result The quaternion that the rotation should be copied to
  80590. */
  80591. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80592. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80593. if (mesh === void 0) { mesh = null; }
  80594. if (space == BABYLON.Space.LOCAL) {
  80595. this._decompose();
  80596. result.copyFrom(this._localRotation);
  80597. }
  80598. else {
  80599. var mat = Bone._tmpMats[0];
  80600. var amat = this.getAbsoluteTransform();
  80601. if (mesh) {
  80602. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80603. }
  80604. else {
  80605. mat.copyFrom(amat);
  80606. }
  80607. mat.m[0] *= this._scalingDeterminant;
  80608. mat.m[1] *= this._scalingDeterminant;
  80609. mat.m[2] *= this._scalingDeterminant;
  80610. mat.decompose(undefined, result, undefined);
  80611. }
  80612. };
  80613. /**
  80614. * Get the rotation matrix of the bone in local or world space
  80615. * @param space The space that the rotation should be in
  80616. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80617. * @returns The rotation matrix
  80618. */
  80619. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80621. var result = BABYLON.Matrix.Identity();
  80622. this.getRotationMatrixToRef(space, mesh, result);
  80623. return result;
  80624. };
  80625. /**
  80626. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80627. * @param space The space that the rotation should be in
  80628. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80629. * @param result The quaternion that the rotation should be copied to
  80630. */
  80631. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80633. if (space == BABYLON.Space.LOCAL) {
  80634. this.getLocalMatrix().getRotationMatrixToRef(result);
  80635. }
  80636. else {
  80637. var mat = Bone._tmpMats[0];
  80638. var amat = this.getAbsoluteTransform();
  80639. if (mesh) {
  80640. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80641. }
  80642. else {
  80643. mat.copyFrom(amat);
  80644. }
  80645. mat.m[0] *= this._scalingDeterminant;
  80646. mat.m[1] *= this._scalingDeterminant;
  80647. mat.m[2] *= this._scalingDeterminant;
  80648. mat.getRotationMatrixToRef(result);
  80649. }
  80650. };
  80651. /**
  80652. * Get the world position of a point that is in the local space of the bone
  80653. * @param position The local position
  80654. * @param mesh The mesh that this bone is attached to
  80655. * @returns The world position
  80656. */
  80657. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80658. if (mesh === void 0) { mesh = null; }
  80659. var result = BABYLON.Vector3.Zero();
  80660. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80661. return result;
  80662. };
  80663. /**
  80664. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80665. * @param position The local position
  80666. * @param mesh The mesh that this bone is attached to
  80667. * @param result The vector3 that the world position should be copied to
  80668. */
  80669. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80670. if (mesh === void 0) { mesh = null; }
  80671. var wm = null;
  80672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80673. if (mesh) {
  80674. wm = mesh.getWorldMatrix();
  80675. }
  80676. this._skeleton.computeAbsoluteTransforms();
  80677. var tmat = Bone._tmpMats[0];
  80678. if (mesh && wm) {
  80679. tmat.copyFrom(this.getAbsoluteTransform());
  80680. tmat.multiplyToRef(wm, tmat);
  80681. }
  80682. else {
  80683. tmat = this.getAbsoluteTransform();
  80684. }
  80685. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80686. };
  80687. /**
  80688. * Get the local position of a point that is in world space
  80689. * @param position The world position
  80690. * @param mesh The mesh that this bone is attached to
  80691. * @returns The local position
  80692. */
  80693. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80694. if (mesh === void 0) { mesh = null; }
  80695. var result = BABYLON.Vector3.Zero();
  80696. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80697. return result;
  80698. };
  80699. /**
  80700. * Get the local position of a point that is in world space and copy it to the result param
  80701. * @param position The world position
  80702. * @param mesh The mesh that this bone is attached to
  80703. * @param result The vector3 that the local position should be copied to
  80704. */
  80705. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80706. if (mesh === void 0) { mesh = null; }
  80707. var wm = null;
  80708. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80709. if (mesh) {
  80710. wm = mesh.getWorldMatrix();
  80711. }
  80712. this._skeleton.computeAbsoluteTransforms();
  80713. var tmat = Bone._tmpMats[0];
  80714. tmat.copyFrom(this.getAbsoluteTransform());
  80715. if (mesh && wm) {
  80716. tmat.multiplyToRef(wm, tmat);
  80717. }
  80718. tmat.invert();
  80719. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80720. };
  80721. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80722. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80723. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80724. return Bone;
  80725. }(BABYLON.Node));
  80726. BABYLON.Bone = Bone;
  80727. })(BABYLON || (BABYLON = {}));
  80728. //# sourceMappingURL=babylon.bone.js.map
  80729. var BABYLON;
  80730. (function (BABYLON) {
  80731. /**
  80732. * Class used to apply inverse kinematics to bones
  80733. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80734. */
  80735. var BoneIKController = /** @class */ (function () {
  80736. /**
  80737. * Creates a new BoneIKController
  80738. * @param mesh defines the mesh to control
  80739. * @param bone defines the bone to control
  80740. * @param options defines options to set up the controller
  80741. */
  80742. function BoneIKController(mesh, bone, options) {
  80743. /**
  80744. * Gets or sets the target position
  80745. */
  80746. this.targetPosition = BABYLON.Vector3.Zero();
  80747. /**
  80748. * Gets or sets the pole target position
  80749. */
  80750. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80751. /**
  80752. * Gets or sets the pole target local offset
  80753. */
  80754. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80755. /**
  80756. * Gets or sets the pole angle
  80757. */
  80758. this.poleAngle = 0;
  80759. /**
  80760. * 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)
  80761. */
  80762. this.slerpAmount = 1;
  80763. this._bone1Quat = BABYLON.Quaternion.Identity();
  80764. this._bone1Mat = BABYLON.Matrix.Identity();
  80765. this._bone2Ang = Math.PI;
  80766. this._maxAngle = Math.PI;
  80767. this._rightHandedSystem = false;
  80768. this._bendAxis = BABYLON.Vector3.Right();
  80769. this._slerping = false;
  80770. this._adjustRoll = 0;
  80771. this._bone2 = bone;
  80772. this._bone1 = bone.getParent();
  80773. if (!this._bone1) {
  80774. return;
  80775. }
  80776. this.mesh = mesh;
  80777. var bonePos = bone.getPosition();
  80778. if (bone.getAbsoluteTransform().determinant() > 0) {
  80779. this._rightHandedSystem = true;
  80780. this._bendAxis.x = 0;
  80781. this._bendAxis.y = 0;
  80782. this._bendAxis.z = -1;
  80783. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80784. this._adjustRoll = Math.PI * .5;
  80785. this._bendAxis.z = 1;
  80786. }
  80787. }
  80788. if (this._bone1.length) {
  80789. var boneScale1 = this._bone1.getScale();
  80790. var boneScale2 = this._bone2.getScale();
  80791. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80792. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80793. }
  80794. else if (this._bone1.children[0]) {
  80795. mesh.computeWorldMatrix(true);
  80796. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80797. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80798. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80799. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80800. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80801. }
  80802. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80803. this.maxAngle = Math.PI;
  80804. if (options) {
  80805. if (options.targetMesh) {
  80806. this.targetMesh = options.targetMesh;
  80807. this.targetMesh.computeWorldMatrix(true);
  80808. }
  80809. if (options.poleTargetMesh) {
  80810. this.poleTargetMesh = options.poleTargetMesh;
  80811. this.poleTargetMesh.computeWorldMatrix(true);
  80812. }
  80813. else if (options.poleTargetBone) {
  80814. this.poleTargetBone = options.poleTargetBone;
  80815. }
  80816. else if (this._bone1.getParent()) {
  80817. this.poleTargetBone = this._bone1.getParent();
  80818. }
  80819. if (options.poleTargetLocalOffset) {
  80820. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80821. }
  80822. if (options.poleAngle) {
  80823. this.poleAngle = options.poleAngle;
  80824. }
  80825. if (options.bendAxis) {
  80826. this._bendAxis.copyFrom(options.bendAxis);
  80827. }
  80828. if (options.maxAngle) {
  80829. this.maxAngle = options.maxAngle;
  80830. }
  80831. if (options.slerpAmount) {
  80832. this.slerpAmount = options.slerpAmount;
  80833. }
  80834. }
  80835. }
  80836. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80837. /**
  80838. * Gets or sets maximum allowed angle
  80839. */
  80840. get: function () {
  80841. return this._maxAngle;
  80842. },
  80843. set: function (value) {
  80844. this._setMaxAngle(value);
  80845. },
  80846. enumerable: true,
  80847. configurable: true
  80848. });
  80849. BoneIKController.prototype._setMaxAngle = function (ang) {
  80850. if (ang < 0) {
  80851. ang = 0;
  80852. }
  80853. if (ang > Math.PI || ang == undefined) {
  80854. ang = Math.PI;
  80855. }
  80856. this._maxAngle = ang;
  80857. var a = this._bone1Length;
  80858. var b = this._bone2Length;
  80859. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80860. };
  80861. /**
  80862. * Force the controller to update the bones
  80863. */
  80864. BoneIKController.prototype.update = function () {
  80865. var bone1 = this._bone1;
  80866. if (!bone1) {
  80867. return;
  80868. }
  80869. var target = this.targetPosition;
  80870. var poleTarget = this.poleTargetPosition;
  80871. var mat1 = BoneIKController._tmpMats[0];
  80872. var mat2 = BoneIKController._tmpMats[1];
  80873. if (this.targetMesh) {
  80874. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80875. }
  80876. if (this.poleTargetBone) {
  80877. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80878. }
  80879. else if (this.poleTargetMesh) {
  80880. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80881. }
  80882. var bonePos = BoneIKController._tmpVecs[0];
  80883. var zaxis = BoneIKController._tmpVecs[1];
  80884. var xaxis = BoneIKController._tmpVecs[2];
  80885. var yaxis = BoneIKController._tmpVecs[3];
  80886. var upAxis = BoneIKController._tmpVecs[4];
  80887. var _tmpQuat = BoneIKController._tmpQuat;
  80888. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80889. poleTarget.subtractToRef(bonePos, upAxis);
  80890. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80891. upAxis.y = 1;
  80892. }
  80893. else {
  80894. upAxis.normalize();
  80895. }
  80896. target.subtractToRef(bonePos, yaxis);
  80897. yaxis.normalize();
  80898. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80899. zaxis.normalize();
  80900. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80901. xaxis.normalize();
  80902. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80903. var a = this._bone1Length;
  80904. var b = this._bone2Length;
  80905. var c = BABYLON.Vector3.Distance(bonePos, target);
  80906. if (this._maxReach > 0) {
  80907. c = Math.min(this._maxReach, c);
  80908. }
  80909. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80910. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80911. if (acosa > 1) {
  80912. acosa = 1;
  80913. }
  80914. if (acosb > 1) {
  80915. acosb = 1;
  80916. }
  80917. if (acosa < -1) {
  80918. acosa = -1;
  80919. }
  80920. if (acosb < -1) {
  80921. acosb = -1;
  80922. }
  80923. var angA = Math.acos(acosa);
  80924. var angB = Math.acos(acosb);
  80925. var angC = -angA - angB;
  80926. if (this._rightHandedSystem) {
  80927. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80928. mat2.multiplyToRef(mat1, mat1);
  80929. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80930. mat2.multiplyToRef(mat1, mat1);
  80931. }
  80932. else {
  80933. var _tmpVec = BoneIKController._tmpVecs[5];
  80934. _tmpVec.copyFrom(this._bendAxis);
  80935. _tmpVec.x *= -1;
  80936. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80937. mat2.multiplyToRef(mat1, mat1);
  80938. }
  80939. if (this.poleAngle) {
  80940. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80941. mat1.multiplyToRef(mat2, mat1);
  80942. }
  80943. if (this._bone1) {
  80944. if (this.slerpAmount < 1) {
  80945. if (!this._slerping) {
  80946. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80947. }
  80948. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80949. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80950. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80951. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80952. this._slerping = true;
  80953. }
  80954. else {
  80955. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80956. this._bone1Mat.copyFrom(mat1);
  80957. this._slerping = false;
  80958. }
  80959. }
  80960. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80961. this._bone2Ang = angC;
  80962. };
  80963. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80964. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80965. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80966. return BoneIKController;
  80967. }());
  80968. BABYLON.BoneIKController = BoneIKController;
  80969. })(BABYLON || (BABYLON = {}));
  80970. //# sourceMappingURL=babylon.boneIKController.js.map
  80971. var BABYLON;
  80972. (function (BABYLON) {
  80973. /**
  80974. * Class used to make a bone look toward a point in space
  80975. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80976. */
  80977. var BoneLookController = /** @class */ (function () {
  80978. /**
  80979. * Create a BoneLookController
  80980. * @param mesh the mesh that the bone belongs to
  80981. * @param bone the bone that will be looking to the target
  80982. * @param target the target Vector3 to look at
  80983. * @param settings optional settings:
  80984. * * maxYaw: the maximum angle the bone will yaw to
  80985. * * minYaw: the minimum angle the bone will yaw to
  80986. * * maxPitch: the maximum angle the bone will pitch to
  80987. * * minPitch: the minimum angle the bone will yaw to
  80988. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80989. * * upAxis: the up axis of the coordinate system
  80990. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80991. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80992. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80993. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80994. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80995. * * adjustRoll: used to make an adjustment to the roll of the bone
  80996. **/
  80997. function BoneLookController(mesh, bone, target, options) {
  80998. /**
  80999. * The up axis of the coordinate system that is used when the bone is rotated
  81000. */
  81001. this.upAxis = BABYLON.Vector3.Up();
  81002. /**
  81003. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  81004. */
  81005. this.upAxisSpace = BABYLON.Space.LOCAL;
  81006. /**
  81007. * Used to make an adjustment to the yaw of the bone
  81008. */
  81009. this.adjustYaw = 0;
  81010. /**
  81011. * Used to make an adjustment to the pitch of the bone
  81012. */
  81013. this.adjustPitch = 0;
  81014. /**
  81015. * Used to make an adjustment to the roll of the bone
  81016. */
  81017. this.adjustRoll = 0;
  81018. /**
  81019. * 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)
  81020. */
  81021. this.slerpAmount = 1;
  81022. this._boneQuat = BABYLON.Quaternion.Identity();
  81023. this._slerping = false;
  81024. this._firstFrameSkipped = false;
  81025. this._fowardAxis = BABYLON.Vector3.Forward();
  81026. this.mesh = mesh;
  81027. this.bone = bone;
  81028. this.target = target;
  81029. if (options) {
  81030. if (options.adjustYaw) {
  81031. this.adjustYaw = options.adjustYaw;
  81032. }
  81033. if (options.adjustPitch) {
  81034. this.adjustPitch = options.adjustPitch;
  81035. }
  81036. if (options.adjustRoll) {
  81037. this.adjustRoll = options.adjustRoll;
  81038. }
  81039. if (options.maxYaw != null) {
  81040. this.maxYaw = options.maxYaw;
  81041. }
  81042. else {
  81043. this.maxYaw = Math.PI;
  81044. }
  81045. if (options.minYaw != null) {
  81046. this.minYaw = options.minYaw;
  81047. }
  81048. else {
  81049. this.minYaw = -Math.PI;
  81050. }
  81051. if (options.maxPitch != null) {
  81052. this.maxPitch = options.maxPitch;
  81053. }
  81054. else {
  81055. this.maxPitch = Math.PI;
  81056. }
  81057. if (options.minPitch != null) {
  81058. this.minPitch = options.minPitch;
  81059. }
  81060. else {
  81061. this.minPitch = -Math.PI;
  81062. }
  81063. if (options.slerpAmount != null) {
  81064. this.slerpAmount = options.slerpAmount;
  81065. }
  81066. if (options.upAxis != null) {
  81067. this.upAxis = options.upAxis;
  81068. }
  81069. if (options.upAxisSpace != null) {
  81070. this.upAxisSpace = options.upAxisSpace;
  81071. }
  81072. if (options.yawAxis != null || options.pitchAxis != null) {
  81073. var newYawAxis = BABYLON.Axis.Y;
  81074. var newPitchAxis = BABYLON.Axis.X;
  81075. if (options.yawAxis != null) {
  81076. newYawAxis = options.yawAxis.clone();
  81077. newYawAxis.normalize();
  81078. }
  81079. if (options.pitchAxis != null) {
  81080. newPitchAxis = options.pitchAxis.clone();
  81081. newPitchAxis.normalize();
  81082. }
  81083. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81084. this._transformYawPitch = BABYLON.Matrix.Identity();
  81085. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81086. this._transformYawPitchInv = this._transformYawPitch.clone();
  81087. this._transformYawPitch.invert();
  81088. }
  81089. }
  81090. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81091. this.upAxisSpace = BABYLON.Space.LOCAL;
  81092. }
  81093. }
  81094. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81095. /**
  81096. * Gets or sets the minimum yaw angle that the bone can look to
  81097. */
  81098. get: function () {
  81099. return this._minYaw;
  81100. },
  81101. set: function (value) {
  81102. this._minYaw = value;
  81103. this._minYawSin = Math.sin(value);
  81104. this._minYawCos = Math.cos(value);
  81105. if (this._maxYaw != null) {
  81106. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81107. this._yawRange = this._maxYaw - this._minYaw;
  81108. }
  81109. },
  81110. enumerable: true,
  81111. configurable: true
  81112. });
  81113. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81114. /**
  81115. * Gets or sets the maximum yaw angle that the bone can look to
  81116. */
  81117. get: function () {
  81118. return this._maxYaw;
  81119. },
  81120. set: function (value) {
  81121. this._maxYaw = value;
  81122. this._maxYawSin = Math.sin(value);
  81123. this._maxYawCos = Math.cos(value);
  81124. if (this._minYaw != null) {
  81125. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81126. this._yawRange = this._maxYaw - this._minYaw;
  81127. }
  81128. },
  81129. enumerable: true,
  81130. configurable: true
  81131. });
  81132. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81133. /**
  81134. * Gets or sets the minimum pitch angle that the bone can look to
  81135. */
  81136. get: function () {
  81137. return this._minPitch;
  81138. },
  81139. set: function (value) {
  81140. this._minPitch = value;
  81141. this._minPitchTan = Math.tan(value);
  81142. },
  81143. enumerable: true,
  81144. configurable: true
  81145. });
  81146. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81147. /**
  81148. * Gets or sets the maximum pitch angle that the bone can look to
  81149. */
  81150. get: function () {
  81151. return this._maxPitch;
  81152. },
  81153. set: function (value) {
  81154. this._maxPitch = value;
  81155. this._maxPitchTan = Math.tan(value);
  81156. },
  81157. enumerable: true,
  81158. configurable: true
  81159. });
  81160. /**
  81161. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81162. */
  81163. BoneLookController.prototype.update = function () {
  81164. //skip the first frame when slerping so that the mesh rotation is correct
  81165. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81166. this._firstFrameSkipped = true;
  81167. return;
  81168. }
  81169. var bone = this.bone;
  81170. var bonePos = BoneLookController._tmpVecs[0];
  81171. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81172. var target = this.target;
  81173. var _tmpMat1 = BoneLookController._tmpMats[0];
  81174. var _tmpMat2 = BoneLookController._tmpMats[1];
  81175. var mesh = this.mesh;
  81176. var parentBone = bone.getParent();
  81177. var upAxis = BoneLookController._tmpVecs[1];
  81178. upAxis.copyFrom(this.upAxis);
  81179. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81180. if (this._transformYawPitch) {
  81181. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81182. }
  81183. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81184. }
  81185. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81186. mesh.getDirectionToRef(upAxis, upAxis);
  81187. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81188. upAxis.normalize();
  81189. }
  81190. }
  81191. var checkYaw = false;
  81192. var checkPitch = false;
  81193. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81194. checkYaw = true;
  81195. }
  81196. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81197. checkPitch = true;
  81198. }
  81199. if (checkYaw || checkPitch) {
  81200. var spaceMat = BoneLookController._tmpMats[2];
  81201. var spaceMatInv = BoneLookController._tmpMats[3];
  81202. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81203. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81204. }
  81205. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81206. spaceMat.copyFrom(mesh.getWorldMatrix());
  81207. }
  81208. else {
  81209. var forwardAxis = BoneLookController._tmpVecs[2];
  81210. forwardAxis.copyFrom(this._fowardAxis);
  81211. if (this._transformYawPitch) {
  81212. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81213. }
  81214. if (parentBone) {
  81215. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81216. }
  81217. else {
  81218. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81219. }
  81220. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81221. rightAxis.normalize();
  81222. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81223. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81224. }
  81225. spaceMat.invertToRef(spaceMatInv);
  81226. var xzlen = null;
  81227. if (checkPitch) {
  81228. var localTarget = BoneLookController._tmpVecs[3];
  81229. target.subtractToRef(bonePos, localTarget);
  81230. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81231. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81232. var pitch = Math.atan2(localTarget.y, xzlen);
  81233. var newPitch = pitch;
  81234. if (pitch > this._maxPitch) {
  81235. localTarget.y = this._maxPitchTan * xzlen;
  81236. newPitch = this._maxPitch;
  81237. }
  81238. else if (pitch < this._minPitch) {
  81239. localTarget.y = this._minPitchTan * xzlen;
  81240. newPitch = this._minPitch;
  81241. }
  81242. if (pitch != newPitch) {
  81243. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81244. localTarget.addInPlace(bonePos);
  81245. target = localTarget;
  81246. }
  81247. }
  81248. if (checkYaw) {
  81249. var localTarget = BoneLookController._tmpVecs[4];
  81250. target.subtractToRef(bonePos, localTarget);
  81251. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81252. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81253. var newYaw = yaw;
  81254. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81255. if (xzlen == null) {
  81256. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81257. }
  81258. if (this._yawRange > Math.PI) {
  81259. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81260. localTarget.z = this._maxYawCos * xzlen;
  81261. localTarget.x = this._maxYawSin * xzlen;
  81262. newYaw = this._maxYaw;
  81263. }
  81264. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81265. localTarget.z = this._minYawCos * xzlen;
  81266. localTarget.x = this._minYawSin * xzlen;
  81267. newYaw = this._minYaw;
  81268. }
  81269. }
  81270. else {
  81271. if (yaw > this._maxYaw) {
  81272. localTarget.z = this._maxYawCos * xzlen;
  81273. localTarget.x = this._maxYawSin * xzlen;
  81274. newYaw = this._maxYaw;
  81275. }
  81276. else if (yaw < this._minYaw) {
  81277. localTarget.z = this._minYawCos * xzlen;
  81278. localTarget.x = this._minYawSin * xzlen;
  81279. newYaw = this._minYaw;
  81280. }
  81281. }
  81282. }
  81283. if (this._slerping && this._yawRange > Math.PI) {
  81284. //are we going to be crossing into the min/max region?
  81285. var boneFwd = BoneLookController._tmpVecs[8];
  81286. boneFwd.copyFrom(BABYLON.Axis.Z);
  81287. if (this._transformYawPitch) {
  81288. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81289. }
  81290. var boneRotMat = BoneLookController._tmpMats[4];
  81291. this._boneQuat.toRotationMatrix(boneRotMat);
  81292. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81293. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81294. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81295. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81296. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81297. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81298. if (angBtwTar > angBtwMidYaw) {
  81299. if (xzlen == null) {
  81300. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81301. }
  81302. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81303. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81304. if (angBtwMin < angBtwMax) {
  81305. newYaw = boneYaw + Math.PI * .75;
  81306. localTarget.z = Math.cos(newYaw) * xzlen;
  81307. localTarget.x = Math.sin(newYaw) * xzlen;
  81308. }
  81309. else {
  81310. newYaw = boneYaw - Math.PI * .75;
  81311. localTarget.z = Math.cos(newYaw) * xzlen;
  81312. localTarget.x = Math.sin(newYaw) * xzlen;
  81313. }
  81314. }
  81315. }
  81316. if (yaw != newYaw) {
  81317. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81318. localTarget.addInPlace(bonePos);
  81319. target = localTarget;
  81320. }
  81321. }
  81322. }
  81323. var zaxis = BoneLookController._tmpVecs[5];
  81324. var xaxis = BoneLookController._tmpVecs[6];
  81325. var yaxis = BoneLookController._tmpVecs[7];
  81326. var _tmpQuat = BoneLookController._tmpQuat;
  81327. target.subtractToRef(bonePos, zaxis);
  81328. zaxis.normalize();
  81329. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81330. xaxis.normalize();
  81331. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81332. yaxis.normalize();
  81333. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81334. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81335. return;
  81336. }
  81337. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81338. return;
  81339. }
  81340. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81341. return;
  81342. }
  81343. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81344. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81345. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81346. }
  81347. if (this.slerpAmount < 1) {
  81348. if (!this._slerping) {
  81349. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81350. }
  81351. if (this._transformYawPitch) {
  81352. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81353. }
  81354. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81355. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81356. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81357. this._slerping = true;
  81358. }
  81359. else {
  81360. if (this._transformYawPitch) {
  81361. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81362. }
  81363. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81364. this._slerping = false;
  81365. }
  81366. };
  81367. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81368. var angDiff = ang2 - ang1;
  81369. angDiff %= Math.PI * 2;
  81370. if (angDiff > Math.PI) {
  81371. angDiff -= Math.PI * 2;
  81372. }
  81373. else if (angDiff < -Math.PI) {
  81374. angDiff += Math.PI * 2;
  81375. }
  81376. return angDiff;
  81377. };
  81378. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81379. ang1 %= (2 * Math.PI);
  81380. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81381. ang2 %= (2 * Math.PI);
  81382. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81383. var ab = 0;
  81384. if (ang1 < ang2) {
  81385. ab = ang2 - ang1;
  81386. }
  81387. else {
  81388. ab = ang1 - ang2;
  81389. }
  81390. if (ab > Math.PI) {
  81391. ab = Math.PI * 2 - ab;
  81392. }
  81393. return ab;
  81394. };
  81395. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81396. ang %= (2 * Math.PI);
  81397. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81398. ang1 %= (2 * Math.PI);
  81399. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81400. ang2 %= (2 * Math.PI);
  81401. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81402. if (ang1 < ang2) {
  81403. if (ang > ang1 && ang < ang2) {
  81404. return true;
  81405. }
  81406. }
  81407. else {
  81408. if (ang > ang2 && ang < ang1) {
  81409. return true;
  81410. }
  81411. }
  81412. return false;
  81413. };
  81414. 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()];
  81415. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81416. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81417. return BoneLookController;
  81418. }());
  81419. BABYLON.BoneLookController = BoneLookController;
  81420. })(BABYLON || (BABYLON = {}));
  81421. //# sourceMappingURL=babylon.boneLookController.js.map
  81422. var BABYLON;
  81423. (function (BABYLON) {
  81424. /**
  81425. * Class used to handle skinning animations
  81426. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81427. */
  81428. var Skeleton = /** @class */ (function () {
  81429. /**
  81430. * Creates a new skeleton
  81431. * @param name defines the skeleton name
  81432. * @param id defines the skeleton Id
  81433. * @param scene defines the hosting scene
  81434. */
  81435. function Skeleton(
  81436. /** defines the skeleton name */
  81437. name,
  81438. /** defines the skeleton Id */
  81439. id, scene) {
  81440. this.name = name;
  81441. this.id = id;
  81442. /**
  81443. * Gets the list of child bones
  81444. */
  81445. this.bones = new Array();
  81446. /**
  81447. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81448. */
  81449. this.needInitialSkinMatrix = false;
  81450. this._isDirty = true;
  81451. this._meshesWithPoseMatrix = new Array();
  81452. this._identity = BABYLON.Matrix.Identity();
  81453. this._ranges = {};
  81454. this._lastAbsoluteTransformsUpdateId = -1;
  81455. /**
  81456. * Specifies if the skeleton should be serialized
  81457. */
  81458. this.doNotSerialize = false;
  81459. this._animationPropertiesOverride = null;
  81460. // Events
  81461. /**
  81462. * An observable triggered before computing the skeleton's matrices
  81463. */
  81464. this.onBeforeComputeObservable = new BABYLON.Observable();
  81465. this.bones = [];
  81466. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81467. scene.skeletons.push(this);
  81468. //make sure it will recalculate the matrix next time prepare is called.
  81469. this._isDirty = true;
  81470. }
  81471. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81472. /**
  81473. * Gets or sets the animation properties override
  81474. */
  81475. get: function () {
  81476. if (!this._animationPropertiesOverride) {
  81477. return this._scene.animationPropertiesOverride;
  81478. }
  81479. return this._animationPropertiesOverride;
  81480. },
  81481. set: function (value) {
  81482. this._animationPropertiesOverride = value;
  81483. },
  81484. enumerable: true,
  81485. configurable: true
  81486. });
  81487. // Members
  81488. /**
  81489. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81490. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81491. * @returns a Float32Array containing matrices data
  81492. */
  81493. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81494. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81495. return mesh._bonesTransformMatrices;
  81496. }
  81497. if (!this._transformMatrices) {
  81498. this.prepare();
  81499. }
  81500. return this._transformMatrices;
  81501. };
  81502. /**
  81503. * Gets the current hosting scene
  81504. * @returns a scene object
  81505. */
  81506. Skeleton.prototype.getScene = function () {
  81507. return this._scene;
  81508. };
  81509. // Methods
  81510. /**
  81511. * Gets a string representing the current skeleton data
  81512. * @param fullDetails defines a boolean indicating if we want a verbose version
  81513. * @returns a string representing the current skeleton data
  81514. */
  81515. Skeleton.prototype.toString = function (fullDetails) {
  81516. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81517. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81518. if (fullDetails) {
  81519. ret += ", Ranges: {";
  81520. var first = true;
  81521. for (var name_1 in this._ranges) {
  81522. if (first) {
  81523. ret += ", ";
  81524. first = false;
  81525. }
  81526. ret += name_1;
  81527. }
  81528. ret += "}";
  81529. }
  81530. return ret;
  81531. };
  81532. /**
  81533. * Get bone's index searching by name
  81534. * @param name defines bone's name to search for
  81535. * @return the indice of the bone. Returns -1 if not found
  81536. */
  81537. Skeleton.prototype.getBoneIndexByName = function (name) {
  81538. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81539. if (this.bones[boneIndex].name === name) {
  81540. return boneIndex;
  81541. }
  81542. }
  81543. return -1;
  81544. };
  81545. /**
  81546. * Creater a new animation range
  81547. * @param name defines the name of the range
  81548. * @param from defines the start key
  81549. * @param to defines the end key
  81550. */
  81551. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81552. // check name not already in use
  81553. if (!this._ranges[name]) {
  81554. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81555. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81556. if (this.bones[i].animations[0]) {
  81557. this.bones[i].animations[0].createRange(name, from, to);
  81558. }
  81559. }
  81560. }
  81561. };
  81562. /**
  81563. * Delete a specific animation range
  81564. * @param name defines the name of the range
  81565. * @param deleteFrames defines if frames must be removed as well
  81566. */
  81567. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81568. if (deleteFrames === void 0) { deleteFrames = true; }
  81569. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81570. if (this.bones[i].animations[0]) {
  81571. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81572. }
  81573. }
  81574. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81575. };
  81576. /**
  81577. * Gets a specific animation range
  81578. * @param name defines the name of the range to look for
  81579. * @returns the requested animation range or null if not found
  81580. */
  81581. Skeleton.prototype.getAnimationRange = function (name) {
  81582. return this._ranges[name];
  81583. };
  81584. /**
  81585. * Gets the list of all animation ranges defined on this skeleton
  81586. * @returns an array
  81587. */
  81588. Skeleton.prototype.getAnimationRanges = function () {
  81589. var animationRanges = [];
  81590. var name;
  81591. var i = 0;
  81592. for (name in this._ranges) {
  81593. animationRanges[i] = this._ranges[name];
  81594. i++;
  81595. }
  81596. return animationRanges;
  81597. };
  81598. /**
  81599. * Copy animation range from a source skeleton.
  81600. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81601. * @param source defines the source skeleton
  81602. * @param name defines the name of the range to copy
  81603. * @param rescaleAsRequired defines if rescaling must be applied if required
  81604. * @returns true if operation was successful
  81605. */
  81606. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81607. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81608. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81609. return false;
  81610. }
  81611. var ret = true;
  81612. var frameOffset = this._getHighestAnimationFrame() + 1;
  81613. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81614. var boneDict = {};
  81615. var sourceBones = source.bones;
  81616. var nBones;
  81617. var i;
  81618. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81619. boneDict[sourceBones[i].name] = sourceBones[i];
  81620. }
  81621. if (this.bones.length !== sourceBones.length) {
  81622. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81623. ret = false;
  81624. }
  81625. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81626. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81627. var boneName = this.bones[i].name;
  81628. var sourceBone = boneDict[boneName];
  81629. if (sourceBone) {
  81630. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81631. }
  81632. else {
  81633. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81634. ret = false;
  81635. }
  81636. }
  81637. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81638. var range = source.getAnimationRange(name);
  81639. if (range) {
  81640. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81641. }
  81642. return ret;
  81643. };
  81644. /**
  81645. * Forces the skeleton to go to rest pose
  81646. */
  81647. Skeleton.prototype.returnToRest = function () {
  81648. for (var index = 0; index < this.bones.length; index++) {
  81649. this.bones[index].returnToRest();
  81650. }
  81651. };
  81652. Skeleton.prototype._getHighestAnimationFrame = function () {
  81653. var ret = 0;
  81654. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81655. if (this.bones[i].animations[0]) {
  81656. var highest = this.bones[i].animations[0].getHighestFrame();
  81657. if (ret < highest) {
  81658. ret = highest;
  81659. }
  81660. }
  81661. }
  81662. return ret;
  81663. };
  81664. /**
  81665. * Begin a specific animation range
  81666. * @param name defines the name of the range to start
  81667. * @param loop defines if looping must be turned on (false by default)
  81668. * @param speedRatio defines the speed ratio to apply (1 by default)
  81669. * @param onAnimationEnd defines a callback which will be called when animation will end
  81670. * @returns a new animatable
  81671. */
  81672. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81673. var range = this.getAnimationRange(name);
  81674. if (!range) {
  81675. return null;
  81676. }
  81677. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81678. };
  81679. /** @hidden */
  81680. Skeleton.prototype._markAsDirty = function () {
  81681. this._isDirty = true;
  81682. };
  81683. /** @hidden */
  81684. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81685. this._meshesWithPoseMatrix.push(mesh);
  81686. };
  81687. /** @hidden */
  81688. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81689. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81690. if (index > -1) {
  81691. this._meshesWithPoseMatrix.splice(index, 1);
  81692. }
  81693. };
  81694. /** @hidden */
  81695. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81696. this.onBeforeComputeObservable.notifyObservers(this);
  81697. for (var index = 0; index < this.bones.length; index++) {
  81698. var bone = this.bones[index];
  81699. var parentBone = bone.getParent();
  81700. if (parentBone) {
  81701. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81702. }
  81703. else {
  81704. if (initialSkinMatrix) {
  81705. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81706. }
  81707. else {
  81708. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81709. }
  81710. }
  81711. if (bone._index !== -1) {
  81712. var mappedIndex = bone._index === null ? index : bone._index;
  81713. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81714. }
  81715. }
  81716. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81717. };
  81718. /**
  81719. * Build all resources required to render a skeleton
  81720. */
  81721. Skeleton.prototype.prepare = function () {
  81722. if (!this._isDirty) {
  81723. return;
  81724. }
  81725. if (this.needInitialSkinMatrix) {
  81726. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81727. var mesh = this._meshesWithPoseMatrix[index];
  81728. var poseMatrix = mesh.getPoseMatrix();
  81729. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81730. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81731. }
  81732. if (this._synchronizedWithMesh !== mesh) {
  81733. this._synchronizedWithMesh = mesh;
  81734. // Prepare bones
  81735. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81736. var bone = this.bones[boneIndex];
  81737. if (!bone.getParent()) {
  81738. var matrix = bone.getBaseMatrix();
  81739. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81740. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81741. }
  81742. }
  81743. }
  81744. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81745. }
  81746. }
  81747. else {
  81748. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81749. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81750. }
  81751. this._computeTransformMatrices(this._transformMatrices, null);
  81752. }
  81753. this._isDirty = false;
  81754. this._scene._activeBones.addCount(this.bones.length, false);
  81755. };
  81756. /**
  81757. * Gets the list of animatables currently running for this skeleton
  81758. * @returns an array of animatables
  81759. */
  81760. Skeleton.prototype.getAnimatables = function () {
  81761. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81762. this._animatables = [];
  81763. for (var index = 0; index < this.bones.length; index++) {
  81764. this._animatables.push(this.bones[index]);
  81765. }
  81766. }
  81767. return this._animatables;
  81768. };
  81769. /**
  81770. * Clone the current skeleton
  81771. * @param name defines the name of the new skeleton
  81772. * @param id defines the id of the enw skeleton
  81773. * @returns the new skeleton
  81774. */
  81775. Skeleton.prototype.clone = function (name, id) {
  81776. var result = new Skeleton(name, id || name, this._scene);
  81777. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81778. for (var index = 0; index < this.bones.length; index++) {
  81779. var source = this.bones[index];
  81780. var parentBone = null;
  81781. var parent_1 = source.getParent();
  81782. if (parent_1) {
  81783. var parentIndex = this.bones.indexOf(parent_1);
  81784. parentBone = result.bones[parentIndex];
  81785. }
  81786. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81787. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81788. }
  81789. if (this._ranges) {
  81790. result._ranges = {};
  81791. for (var rangeName in this._ranges) {
  81792. var range = this._ranges[rangeName];
  81793. if (range) {
  81794. result._ranges[rangeName] = range.clone();
  81795. }
  81796. }
  81797. }
  81798. this._isDirty = true;
  81799. return result;
  81800. };
  81801. /**
  81802. * Enable animation blending for this skeleton
  81803. * @param blendingSpeed defines the blending speed to apply
  81804. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81805. */
  81806. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81807. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81808. this.bones.forEach(function (bone) {
  81809. bone.animations.forEach(function (animation) {
  81810. animation.enableBlending = true;
  81811. animation.blendingSpeed = blendingSpeed;
  81812. });
  81813. });
  81814. };
  81815. /**
  81816. * Releases all resources associated with the current skeleton
  81817. */
  81818. Skeleton.prototype.dispose = function () {
  81819. this._meshesWithPoseMatrix = [];
  81820. // Animations
  81821. this.getScene().stopAnimation(this);
  81822. // Remove from scene
  81823. this.getScene().removeSkeleton(this);
  81824. };
  81825. /**
  81826. * Serialize the skeleton in a JSON object
  81827. * @returns a JSON object
  81828. */
  81829. Skeleton.prototype.serialize = function () {
  81830. var serializationObject = {};
  81831. serializationObject.name = this.name;
  81832. serializationObject.id = this.id;
  81833. if (this.dimensionsAtRest) {
  81834. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81835. }
  81836. serializationObject.bones = [];
  81837. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81838. for (var index = 0; index < this.bones.length; index++) {
  81839. var bone = this.bones[index];
  81840. var parent_2 = bone.getParent();
  81841. var serializedBone = {
  81842. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81843. name: bone.name,
  81844. matrix: bone.getBaseMatrix().toArray(),
  81845. rest: bone.getRestPose().toArray()
  81846. };
  81847. serializationObject.bones.push(serializedBone);
  81848. if (bone.length) {
  81849. serializedBone.length = bone.length;
  81850. }
  81851. if (bone.metadata) {
  81852. serializedBone.metadata = bone.metadata;
  81853. }
  81854. if (bone.animations && bone.animations.length > 0) {
  81855. serializedBone.animation = bone.animations[0].serialize();
  81856. }
  81857. serializationObject.ranges = [];
  81858. for (var name in this._ranges) {
  81859. var source = this._ranges[name];
  81860. if (!source) {
  81861. continue;
  81862. }
  81863. var range = {};
  81864. range.name = name;
  81865. range.from = source.from;
  81866. range.to = source.to;
  81867. serializationObject.ranges.push(range);
  81868. }
  81869. }
  81870. return serializationObject;
  81871. };
  81872. /**
  81873. * Creates a new skeleton from serialized data
  81874. * @param parsedSkeleton defines the serialized data
  81875. * @param scene defines the hosting scene
  81876. * @returns a new skeleton
  81877. */
  81878. Skeleton.Parse = function (parsedSkeleton, scene) {
  81879. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81880. if (parsedSkeleton.dimensionsAtRest) {
  81881. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81882. }
  81883. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81884. var index;
  81885. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81886. var parsedBone = parsedSkeleton.bones[index];
  81887. var parentBone = null;
  81888. if (parsedBone.parentBoneIndex > -1) {
  81889. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81890. }
  81891. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81892. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81893. if (parsedBone.length) {
  81894. bone.length = parsedBone.length;
  81895. }
  81896. if (parsedBone.metadata) {
  81897. bone.metadata = parsedBone.metadata;
  81898. }
  81899. if (parsedBone.animation) {
  81900. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81901. }
  81902. }
  81903. // placed after bones, so createAnimationRange can cascade down
  81904. if (parsedSkeleton.ranges) {
  81905. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81906. var data = parsedSkeleton.ranges[index];
  81907. skeleton.createAnimationRange(data.name, data.from, data.to);
  81908. }
  81909. }
  81910. return skeleton;
  81911. };
  81912. /**
  81913. * Compute all node absolute transforms
  81914. * @param forceUpdate defines if computation must be done even if cache is up to date
  81915. */
  81916. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81917. if (forceUpdate === void 0) { forceUpdate = false; }
  81918. var renderId = this._scene.getRenderId();
  81919. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81920. this.bones[0].computeAbsoluteTransforms();
  81921. this._lastAbsoluteTransformsUpdateId = renderId;
  81922. }
  81923. };
  81924. /**
  81925. * Gets the root pose matrix
  81926. * @returns a matrix
  81927. */
  81928. Skeleton.prototype.getPoseMatrix = function () {
  81929. var poseMatrix = null;
  81930. if (this._meshesWithPoseMatrix.length > 0) {
  81931. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81932. }
  81933. return poseMatrix;
  81934. };
  81935. /**
  81936. * Sorts bones per internal index
  81937. */
  81938. Skeleton.prototype.sortBones = function () {
  81939. var bones = new Array();
  81940. var visited = new Array(this.bones.length);
  81941. for (var index = 0; index < this.bones.length; index++) {
  81942. this._sortBones(index, bones, visited);
  81943. }
  81944. this.bones = bones;
  81945. };
  81946. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81947. if (visited[index]) {
  81948. return;
  81949. }
  81950. visited[index] = true;
  81951. var bone = this.bones[index];
  81952. if (bone._index === undefined) {
  81953. bone._index = index;
  81954. }
  81955. var parentBone = bone.getParent();
  81956. if (parentBone) {
  81957. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81958. }
  81959. bones.push(bone);
  81960. };
  81961. return Skeleton;
  81962. }());
  81963. BABYLON.Skeleton = Skeleton;
  81964. })(BABYLON || (BABYLON = {}));
  81965. //# sourceMappingURL=babylon.skeleton.js.map
  81966. var BABYLON;
  81967. (function (BABYLON) {
  81968. /**
  81969. * Class representing spherical polynomial coefficients to the 3rd degree
  81970. */
  81971. var SphericalPolynomial = /** @class */ (function () {
  81972. function SphericalPolynomial() {
  81973. /**
  81974. * The x coefficients of the spherical polynomial
  81975. */
  81976. this.x = BABYLON.Vector3.Zero();
  81977. /**
  81978. * The y coefficients of the spherical polynomial
  81979. */
  81980. this.y = BABYLON.Vector3.Zero();
  81981. /**
  81982. * The z coefficients of the spherical polynomial
  81983. */
  81984. this.z = BABYLON.Vector3.Zero();
  81985. /**
  81986. * The xx coefficients of the spherical polynomial
  81987. */
  81988. this.xx = BABYLON.Vector3.Zero();
  81989. /**
  81990. * The yy coefficients of the spherical polynomial
  81991. */
  81992. this.yy = BABYLON.Vector3.Zero();
  81993. /**
  81994. * The zz coefficients of the spherical polynomial
  81995. */
  81996. this.zz = BABYLON.Vector3.Zero();
  81997. /**
  81998. * The xy coefficients of the spherical polynomial
  81999. */
  82000. this.xy = BABYLON.Vector3.Zero();
  82001. /**
  82002. * The yz coefficients of the spherical polynomial
  82003. */
  82004. this.yz = BABYLON.Vector3.Zero();
  82005. /**
  82006. * The zx coefficients of the spherical polynomial
  82007. */
  82008. this.zx = BABYLON.Vector3.Zero();
  82009. }
  82010. /**
  82011. * Adds an ambient color to the spherical polynomial
  82012. * @param color the color to add
  82013. */
  82014. SphericalPolynomial.prototype.addAmbient = function (color) {
  82015. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82016. this.xx = this.xx.add(colorVector);
  82017. this.yy = this.yy.add(colorVector);
  82018. this.zz = this.zz.add(colorVector);
  82019. };
  82020. /**
  82021. * Scales the spherical polynomial by the given amount
  82022. * @param scale the amount to scale
  82023. */
  82024. SphericalPolynomial.prototype.scale = function (scale) {
  82025. this.x = this.x.scale(scale);
  82026. this.y = this.y.scale(scale);
  82027. this.z = this.z.scale(scale);
  82028. this.xx = this.xx.scale(scale);
  82029. this.yy = this.yy.scale(scale);
  82030. this.zz = this.zz.scale(scale);
  82031. this.yz = this.yz.scale(scale);
  82032. this.zx = this.zx.scale(scale);
  82033. this.xy = this.xy.scale(scale);
  82034. };
  82035. /**
  82036. * Gets the spherical polynomial from harmonics
  82037. * @param harmonics the spherical harmonics
  82038. * @returns the spherical polynomial
  82039. */
  82040. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82041. var result = new SphericalPolynomial();
  82042. result.x = harmonics.l11.scale(1.02333);
  82043. result.y = harmonics.l1_1.scale(1.02333);
  82044. result.z = harmonics.l10.scale(1.02333);
  82045. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82046. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82047. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82048. result.yz = harmonics.l2_1.scale(0.858086);
  82049. result.zx = harmonics.l21.scale(0.858086);
  82050. result.xy = harmonics.l2_2.scale(0.858086);
  82051. result.scale(1.0 / Math.PI);
  82052. return result;
  82053. };
  82054. /**
  82055. * Constructs a spherical polynomial from an array.
  82056. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82057. * @returns the spherical polynomial
  82058. */
  82059. SphericalPolynomial.FromArray = function (data) {
  82060. var sp = new SphericalPolynomial();
  82061. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82062. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82063. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82064. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82065. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82066. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82067. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82068. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82069. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82070. return sp;
  82071. };
  82072. return SphericalPolynomial;
  82073. }());
  82074. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82075. /**
  82076. * Class representing spherical harmonics coefficients to the 3rd degree
  82077. */
  82078. var SphericalHarmonics = /** @class */ (function () {
  82079. function SphericalHarmonics() {
  82080. /**
  82081. * The l0,0 coefficients of the spherical harmonics
  82082. */
  82083. this.l00 = BABYLON.Vector3.Zero();
  82084. /**
  82085. * The l1,-1 coefficients of the spherical harmonics
  82086. */
  82087. this.l1_1 = BABYLON.Vector3.Zero();
  82088. /**
  82089. * The l1,0 coefficients of the spherical harmonics
  82090. */
  82091. this.l10 = BABYLON.Vector3.Zero();
  82092. /**
  82093. * The l1,1 coefficients of the spherical harmonics
  82094. */
  82095. this.l11 = BABYLON.Vector3.Zero();
  82096. /**
  82097. * The l2,-2 coefficients of the spherical harmonics
  82098. */
  82099. this.l2_2 = BABYLON.Vector3.Zero();
  82100. /**
  82101. * The l2,-1 coefficients of the spherical harmonics
  82102. */
  82103. this.l2_1 = BABYLON.Vector3.Zero();
  82104. /**
  82105. * The l2,0 coefficients of the spherical harmonics
  82106. */
  82107. this.l20 = BABYLON.Vector3.Zero();
  82108. /**
  82109. * The l2,1 coefficients of the spherical harmonics
  82110. */
  82111. this.l21 = BABYLON.Vector3.Zero();
  82112. /**
  82113. * The l2,2 coefficients of the spherical harmonics
  82114. */
  82115. this.lL22 = BABYLON.Vector3.Zero();
  82116. }
  82117. /**
  82118. * Adds a light to the spherical harmonics
  82119. * @param direction the direction of the light
  82120. * @param color the color of the light
  82121. * @param deltaSolidAngle the delta solid angle of the light
  82122. */
  82123. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82124. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82125. var c = colorVector.scale(deltaSolidAngle);
  82126. this.l00 = this.l00.add(c.scale(0.282095));
  82127. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82128. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82129. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82130. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82131. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82132. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82133. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82134. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82135. };
  82136. /**
  82137. * Scales the spherical harmonics by the given amount
  82138. * @param scale the amount to scale
  82139. */
  82140. SphericalHarmonics.prototype.scale = function (scale) {
  82141. this.l00 = this.l00.scale(scale);
  82142. this.l1_1 = this.l1_1.scale(scale);
  82143. this.l10 = this.l10.scale(scale);
  82144. this.l11 = this.l11.scale(scale);
  82145. this.l2_2 = this.l2_2.scale(scale);
  82146. this.l2_1 = this.l2_1.scale(scale);
  82147. this.l20 = this.l20.scale(scale);
  82148. this.l21 = this.l21.scale(scale);
  82149. this.lL22 = this.lL22.scale(scale);
  82150. };
  82151. /**
  82152. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82153. *
  82154. * ```
  82155. * E_lm = A_l * L_lm
  82156. * ```
  82157. *
  82158. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82159. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82160. * the scaling factors are given in equation 9.
  82161. */
  82162. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82163. // Constant (Band 0)
  82164. this.l00 = this.l00.scale(3.141593);
  82165. // Linear (Band 1)
  82166. this.l1_1 = this.l1_1.scale(2.094395);
  82167. this.l10 = this.l10.scale(2.094395);
  82168. this.l11 = this.l11.scale(2.094395);
  82169. // Quadratic (Band 2)
  82170. this.l2_2 = this.l2_2.scale(0.785398);
  82171. this.l2_1 = this.l2_1.scale(0.785398);
  82172. this.l20 = this.l20.scale(0.785398);
  82173. this.l21 = this.l21.scale(0.785398);
  82174. this.lL22 = this.lL22.scale(0.785398);
  82175. };
  82176. /**
  82177. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82178. *
  82179. * ```
  82180. * L = (1/pi) * E * rho
  82181. * ```
  82182. *
  82183. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82184. */
  82185. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82186. this.scale(1.0 / Math.PI);
  82187. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82188. // (The pixel shader must apply albedo after texture fetches, etc).
  82189. };
  82190. /**
  82191. * Gets the spherical harmonics from polynomial
  82192. * @param polynomial the spherical polynomial
  82193. * @returns the spherical harmonics
  82194. */
  82195. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82196. var result = new SphericalHarmonics();
  82197. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82198. result.l1_1 = polynomial.y.scale(0.977204);
  82199. result.l10 = polynomial.z.scale(0.977204);
  82200. result.l11 = polynomial.x.scale(0.977204);
  82201. result.l2_2 = polynomial.xy.scale(1.16538);
  82202. result.l2_1 = polynomial.yz.scale(1.16538);
  82203. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82204. result.l21 = polynomial.zx.scale(1.16538);
  82205. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82206. result.scale(Math.PI);
  82207. return result;
  82208. };
  82209. /**
  82210. * Constructs a spherical harmonics from an array.
  82211. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82212. * @returns the spherical harmonics
  82213. */
  82214. SphericalHarmonics.FromArray = function (data) {
  82215. var sh = new SphericalHarmonics();
  82216. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82217. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82218. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82219. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82220. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82221. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82222. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82223. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82224. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82225. return sh;
  82226. };
  82227. return SphericalHarmonics;
  82228. }());
  82229. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82230. })(BABYLON || (BABYLON = {}));
  82231. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82232. var BABYLON;
  82233. (function (BABYLON) {
  82234. var FileFaceOrientation = /** @class */ (function () {
  82235. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82236. this.name = name;
  82237. this.worldAxisForNormal = worldAxisForNormal;
  82238. this.worldAxisForFileX = worldAxisForFileX;
  82239. this.worldAxisForFileY = worldAxisForFileY;
  82240. }
  82241. return FileFaceOrientation;
  82242. }());
  82243. ;
  82244. /**
  82245. * Helper class dealing with the extraction of spherical polynomial dataArray
  82246. * from a cube map.
  82247. */
  82248. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82249. function CubeMapToSphericalPolynomialTools() {
  82250. }
  82251. /**
  82252. * Converts a texture to the according Spherical Polynomial data.
  82253. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82254. *
  82255. * @param texture The texture to extract the information from.
  82256. * @return The Spherical Polynomial data.
  82257. */
  82258. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82259. if (!texture.isCube) {
  82260. // Only supports cube Textures currently.
  82261. return null;
  82262. }
  82263. var size = texture.getSize().width;
  82264. var right = texture.readPixels(0);
  82265. var left = texture.readPixels(1);
  82266. var up;
  82267. var down;
  82268. if (texture.isRenderTarget) {
  82269. up = texture.readPixels(3);
  82270. down = texture.readPixels(2);
  82271. }
  82272. else {
  82273. up = texture.readPixels(2);
  82274. down = texture.readPixels(3);
  82275. }
  82276. var front = texture.readPixels(4);
  82277. var back = texture.readPixels(5);
  82278. var gammaSpace = texture.gammaSpace;
  82279. // Always read as RGBA.
  82280. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82281. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82282. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82283. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82284. }
  82285. var cubeInfo = {
  82286. size: size,
  82287. right: right,
  82288. left: left,
  82289. up: up,
  82290. down: down,
  82291. front: front,
  82292. back: back,
  82293. format: format,
  82294. type: type,
  82295. gammaSpace: gammaSpace,
  82296. };
  82297. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82298. };
  82299. /**
  82300. * Converts a cubemap to the according Spherical Polynomial data.
  82301. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82302. *
  82303. * @param cubeInfo The Cube map to extract the information from.
  82304. * @return The Spherical Polynomial data.
  82305. */
  82306. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82307. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82308. var totalSolidAngle = 0.0;
  82309. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82310. var du = 2.0 / cubeInfo.size;
  82311. var dv = du;
  82312. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82313. var minUV = du * 0.5 - 1.0;
  82314. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82315. var fileFace = this.FileFaces[faceIndex];
  82316. var dataArray = cubeInfo[fileFace.name];
  82317. var v = minUV;
  82318. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82319. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82320. // Because SP is still linear, so summation is fine in that basis.
  82321. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82322. for (var y = 0; y < cubeInfo.size; y++) {
  82323. var u = minUV;
  82324. for (var x = 0; x < cubeInfo.size; x++) {
  82325. // World direction (not normalised)
  82326. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82327. worldDirection.normalize();
  82328. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82329. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82330. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82331. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82332. // Handle Integer types.
  82333. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82334. r /= 255;
  82335. g /= 255;
  82336. b /= 255;
  82337. }
  82338. // Handle Gamma space textures.
  82339. if (cubeInfo.gammaSpace) {
  82340. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82341. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82342. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82343. }
  82344. var color = new BABYLON.Color3(r, g, b);
  82345. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82346. totalSolidAngle += deltaSolidAngle;
  82347. u += du;
  82348. }
  82349. v += dv;
  82350. }
  82351. }
  82352. // Solid angle for entire sphere is 4*pi
  82353. var sphereSolidAngle = 4.0 * Math.PI;
  82354. // Adjust the solid angle to allow for how many faces we processed.
  82355. var facesProcessed = 6.0;
  82356. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82357. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82358. // This is needed because the numerical integration over the cube uses a
  82359. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82360. // and also to compensate for accumulative error due to float precision in the summation.
  82361. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82362. sphericalHarmonics.scale(correctionFactor);
  82363. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82364. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82365. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82366. };
  82367. CubeMapToSphericalPolynomialTools.FileFaces = [
  82368. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82369. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82370. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82371. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82372. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82373. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82374. ];
  82375. return CubeMapToSphericalPolynomialTools;
  82376. }());
  82377. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82378. })(BABYLON || (BABYLON = {}));
  82379. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82380. var BABYLON;
  82381. (function (BABYLON) {
  82382. /**
  82383. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82384. */
  82385. var PanoramaToCubeMapTools = /** @class */ (function () {
  82386. function PanoramaToCubeMapTools() {
  82387. }
  82388. /**
  82389. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82390. *
  82391. * @param float32Array The source data.
  82392. * @param inputWidth The width of the input panorama.
  82393. * @param inputhHeight The height of the input panorama.
  82394. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82395. * @return The cubemap data
  82396. */
  82397. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82398. if (!float32Array) {
  82399. throw "ConvertPanoramaToCubemap: input cannot be null";
  82400. }
  82401. if (float32Array.length != inputWidth * inputHeight * 3) {
  82402. throw "ConvertPanoramaToCubemap: input size is wrong";
  82403. }
  82404. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82405. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82406. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82407. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82408. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82409. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82410. return {
  82411. front: textureFront,
  82412. back: textureBack,
  82413. left: textureLeft,
  82414. right: textureRight,
  82415. up: textureUp,
  82416. down: textureDown,
  82417. size: size,
  82418. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82419. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82420. gammaSpace: false,
  82421. };
  82422. };
  82423. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82424. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82425. var textureArray = new Float32Array(buffer);
  82426. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82427. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82428. var dy = 1 / texSize;
  82429. var fy = 0;
  82430. for (var y = 0; y < texSize; y++) {
  82431. var xv1 = faceData[0];
  82432. var xv2 = faceData[2];
  82433. for (var x = 0; x < texSize; x++) {
  82434. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82435. v.normalize();
  82436. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82437. // 3 channels per pixels
  82438. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82439. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82440. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82441. xv1 = xv1.add(rotDX1);
  82442. xv2 = xv2.add(rotDX2);
  82443. }
  82444. fy += dy;
  82445. }
  82446. return textureArray;
  82447. };
  82448. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82449. var theta = Math.atan2(vDir.z, vDir.x);
  82450. var phi = Math.acos(vDir.y);
  82451. while (theta < -Math.PI)
  82452. theta += 2 * Math.PI;
  82453. while (theta > Math.PI)
  82454. theta -= 2 * Math.PI;
  82455. var dx = theta / Math.PI;
  82456. var dy = phi / Math.PI;
  82457. // recenter.
  82458. dx = dx * 0.5 + 0.5;
  82459. var px = Math.round(dx * inputWidth);
  82460. if (px < 0)
  82461. px = 0;
  82462. else if (px >= inputWidth)
  82463. px = inputWidth - 1;
  82464. var py = Math.round(dy * inputHeight);
  82465. if (py < 0)
  82466. py = 0;
  82467. else if (py >= inputHeight)
  82468. py = inputHeight - 1;
  82469. var inputY = (inputHeight - py - 1);
  82470. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82471. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82472. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82473. return {
  82474. r: r,
  82475. g: g,
  82476. b: b
  82477. };
  82478. };
  82479. PanoramaToCubeMapTools.FACE_FRONT = [
  82480. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82481. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82482. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82483. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82484. ];
  82485. PanoramaToCubeMapTools.FACE_BACK = [
  82486. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82487. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82488. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82489. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82490. ];
  82491. PanoramaToCubeMapTools.FACE_RIGHT = [
  82492. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82493. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82494. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82495. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82496. ];
  82497. PanoramaToCubeMapTools.FACE_LEFT = [
  82498. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82499. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82500. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82501. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82502. ];
  82503. PanoramaToCubeMapTools.FACE_DOWN = [
  82504. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82505. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82506. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82507. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82508. ];
  82509. PanoramaToCubeMapTools.FACE_UP = [
  82510. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82511. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82512. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82513. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82514. ];
  82515. return PanoramaToCubeMapTools;
  82516. }());
  82517. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82518. })(BABYLON || (BABYLON = {}));
  82519. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82520. var BABYLON;
  82521. (function (BABYLON) {
  82522. ;
  82523. /**
  82524. * This groups tools to convert HDR texture to native colors array.
  82525. */
  82526. var HDRTools = /** @class */ (function () {
  82527. function HDRTools() {
  82528. }
  82529. HDRTools.Ldexp = function (mantissa, exponent) {
  82530. if (exponent > 1023) {
  82531. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82532. }
  82533. if (exponent < -1074) {
  82534. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82535. }
  82536. return mantissa * Math.pow(2, exponent);
  82537. };
  82538. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82539. if (exponent > 0) { /*nonzero pixel*/
  82540. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82541. float32array[index + 0] = red * exponent;
  82542. float32array[index + 1] = green * exponent;
  82543. float32array[index + 2] = blue * exponent;
  82544. }
  82545. else {
  82546. float32array[index + 0] = 0;
  82547. float32array[index + 1] = 0;
  82548. float32array[index + 2] = 0;
  82549. }
  82550. };
  82551. HDRTools.readStringLine = function (uint8array, startIndex) {
  82552. var line = "";
  82553. var character = "";
  82554. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82555. character = String.fromCharCode(uint8array[i]);
  82556. if (character == "\n") {
  82557. break;
  82558. }
  82559. line += character;
  82560. }
  82561. return line;
  82562. };
  82563. /**
  82564. * Reads header information from an RGBE texture stored in a native array.
  82565. * More information on this format are available here:
  82566. * https://en.wikipedia.org/wiki/RGBE_image_format
  82567. *
  82568. * @param uint8array The binary file stored in native array.
  82569. * @return The header information.
  82570. */
  82571. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82572. var height = 0;
  82573. var width = 0;
  82574. var line = this.readStringLine(uint8array, 0);
  82575. if (line[0] != '#' || line[1] != '?') {
  82576. throw "Bad HDR Format.";
  82577. }
  82578. var endOfHeader = false;
  82579. var findFormat = false;
  82580. var lineIndex = 0;
  82581. do {
  82582. lineIndex += (line.length + 1);
  82583. line = this.readStringLine(uint8array, lineIndex);
  82584. if (line == "FORMAT=32-bit_rle_rgbe") {
  82585. findFormat = true;
  82586. }
  82587. else if (line.length == 0) {
  82588. endOfHeader = true;
  82589. }
  82590. } while (!endOfHeader);
  82591. if (!findFormat) {
  82592. throw "HDR Bad header format, unsupported FORMAT";
  82593. }
  82594. lineIndex += (line.length + 1);
  82595. line = this.readStringLine(uint8array, lineIndex);
  82596. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82597. var match = sizeRegexp.exec(line);
  82598. // TODO. Support +Y and -X if needed.
  82599. if (!match || match.length < 3) {
  82600. throw "HDR Bad header format, no size";
  82601. }
  82602. width = parseInt(match[2]);
  82603. height = parseInt(match[1]);
  82604. if (width < 8 || width > 0x7fff) {
  82605. throw "HDR Bad header format, unsupported size";
  82606. }
  82607. lineIndex += (line.length + 1);
  82608. return {
  82609. height: height,
  82610. width: width,
  82611. dataPosition: lineIndex
  82612. };
  82613. };
  82614. /**
  82615. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82616. * This RGBE texture needs to store the information as a panorama.
  82617. *
  82618. * More information on this format are available here:
  82619. * https://en.wikipedia.org/wiki/RGBE_image_format
  82620. *
  82621. * @param buffer The binary file stored in an array buffer.
  82622. * @param size The expected size of the extracted cubemap.
  82623. * @return The Cube Map information.
  82624. */
  82625. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82626. var uint8array = new Uint8Array(buffer);
  82627. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82628. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82629. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82630. return cubeMapData;
  82631. };
  82632. /**
  82633. * Returns the pixels data extracted from an RGBE texture.
  82634. * This pixels will be stored left to right up to down in the R G B order in one array.
  82635. *
  82636. * More information on this format are available here:
  82637. * https://en.wikipedia.org/wiki/RGBE_image_format
  82638. *
  82639. * @param uint8array The binary file stored in an array buffer.
  82640. * @param hdrInfo The header information of the file.
  82641. * @return The pixels data in RGB right to left up to down order.
  82642. */
  82643. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82644. // Keep for multi format supports.
  82645. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82646. };
  82647. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82648. var num_scanlines = hdrInfo.height;
  82649. var scanline_width = hdrInfo.width;
  82650. var a, b, c, d, count;
  82651. var dataIndex = hdrInfo.dataPosition;
  82652. var index = 0, endIndex = 0, i = 0;
  82653. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82654. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82655. // 3 channels of 4 bytes per pixel in float.
  82656. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82657. var resultArray = new Float32Array(resultBuffer);
  82658. // read in each successive scanline
  82659. while (num_scanlines > 0) {
  82660. a = uint8array[dataIndex++];
  82661. b = uint8array[dataIndex++];
  82662. c = uint8array[dataIndex++];
  82663. d = uint8array[dataIndex++];
  82664. if (a != 2 || b != 2 || (c & 0x80)) {
  82665. // this file is not run length encoded
  82666. throw "HDR Bad header format, not RLE";
  82667. }
  82668. if (((c << 8) | d) != scanline_width) {
  82669. throw "HDR Bad header format, wrong scan line width";
  82670. }
  82671. index = 0;
  82672. // read each of the four channels for the scanline into the buffer
  82673. for (i = 0; i < 4; i++) {
  82674. endIndex = (i + 1) * scanline_width;
  82675. while (index < endIndex) {
  82676. a = uint8array[dataIndex++];
  82677. b = uint8array[dataIndex++];
  82678. if (a > 128) {
  82679. // a run of the same value
  82680. count = a - 128;
  82681. if ((count == 0) || (count > endIndex - index)) {
  82682. throw "HDR Bad Format, bad scanline data (run)";
  82683. }
  82684. while (count-- > 0) {
  82685. scanLineArray[index++] = b;
  82686. }
  82687. }
  82688. else {
  82689. // a non-run
  82690. count = a;
  82691. if ((count == 0) || (count > endIndex - index)) {
  82692. throw "HDR Bad Format, bad scanline data (non-run)";
  82693. }
  82694. scanLineArray[index++] = b;
  82695. if (--count > 0) {
  82696. for (var j = 0; j < count; j++) {
  82697. scanLineArray[index++] = uint8array[dataIndex++];
  82698. }
  82699. }
  82700. }
  82701. }
  82702. }
  82703. // now convert data from buffer into floats
  82704. for (i = 0; i < scanline_width; i++) {
  82705. a = scanLineArray[i];
  82706. b = scanLineArray[i + scanline_width];
  82707. c = scanLineArray[i + 2 * scanline_width];
  82708. d = scanLineArray[i + 3 * scanline_width];
  82709. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82710. }
  82711. num_scanlines--;
  82712. }
  82713. return resultArray;
  82714. };
  82715. return HDRTools;
  82716. }());
  82717. BABYLON.HDRTools = HDRTools;
  82718. })(BABYLON || (BABYLON = {}));
  82719. //# sourceMappingURL=babylon.hdr.js.map
  82720. var BABYLON;
  82721. (function (BABYLON) {
  82722. /**
  82723. * Sets of helpers addressing the serialization and deserialization of environment texture
  82724. * stored in a BabylonJS env file.
  82725. * Those files are usually stored as .env files.
  82726. */
  82727. var EnvironmentTextureTools = /** @class */ (function () {
  82728. function EnvironmentTextureTools() {
  82729. }
  82730. /**
  82731. * Gets the environment info from an env file.
  82732. * @param data The array buffer containing the .env bytes.
  82733. * @returns the environment file info (the json header) if successfully parsed.
  82734. */
  82735. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82736. var dataView = new DataView(data);
  82737. var pos = 0;
  82738. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82739. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82740. BABYLON.Tools.Error('Not a babylon environment map');
  82741. return null;
  82742. }
  82743. }
  82744. // Read json manifest - collect characters up to null terminator
  82745. var manifestString = '';
  82746. var charCode = 0x00;
  82747. while ((charCode = dataView.getUint8(pos++))) {
  82748. manifestString += String.fromCharCode(charCode);
  82749. }
  82750. var manifest = JSON.parse(manifestString);
  82751. if (manifest.specular) {
  82752. // Extend the header with the position of the payload.
  82753. manifest.specular.specularDataPosition = pos;
  82754. }
  82755. return manifest;
  82756. };
  82757. /**
  82758. * Creates an environment texture from a loaded cube texture.
  82759. * @param texture defines the cube texture to convert in env file
  82760. * @return a promise containing the environment data if succesfull.
  82761. */
  82762. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82763. var _this = this;
  82764. var internalTexture = texture.getInternalTexture();
  82765. if (!internalTexture) {
  82766. return Promise.reject("The cube texture is invalid.");
  82767. }
  82768. if (!texture._prefiltered) {
  82769. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82770. }
  82771. var engine = internalTexture.getEngine();
  82772. if (engine && engine.premultipliedAlpha) {
  82773. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82774. }
  82775. var canvas = engine.getRenderingCanvas();
  82776. if (!canvas) {
  82777. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82778. }
  82779. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82780. if (!engine.getCaps().textureFloatRender) {
  82781. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82782. if (!engine.getCaps().textureHalfFloatRender) {
  82783. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82784. }
  82785. }
  82786. var cubeWidth = internalTexture.width;
  82787. var hostingScene = new BABYLON.Scene(engine);
  82788. var specularTextures = {};
  82789. var promises = [];
  82790. // Read and collect all mipmaps data from the cube.
  82791. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82792. mipmapsCount = Math.round(mipmapsCount);
  82793. var _loop_1 = function (i) {
  82794. var faceWidth = Math.pow(2, mipmapsCount - i);
  82795. var _loop_2 = function (face) {
  82796. var data = texture.readPixels(face, i);
  82797. // Creates a temp texture with the face data.
  82798. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82799. // And rgbdEncode them.
  82800. var promise = new Promise(function (resolve, reject) {
  82801. 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);
  82802. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82803. rgbdPostProcess.onApply = function (effect) {
  82804. effect._bindTexture("textureSampler", tempTexture);
  82805. };
  82806. // As the process needs to happen on the main canvas, keep track of the current size
  82807. var currentW = engine.getRenderWidth();
  82808. var currentH = engine.getRenderHeight();
  82809. // Set the desired size for the texture
  82810. engine.setSize(faceWidth, faceWidth);
  82811. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82812. // Reading datas from WebGL
  82813. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82814. var fileReader = new FileReader();
  82815. fileReader.onload = function (event) {
  82816. var arrayBuffer = event.target.result;
  82817. specularTextures[i * 6 + face] = arrayBuffer;
  82818. resolve();
  82819. };
  82820. fileReader.readAsArrayBuffer(blob);
  82821. });
  82822. // Reapply the previous canvas size
  82823. engine.setSize(currentW, currentH);
  82824. });
  82825. });
  82826. promises.push(promise);
  82827. };
  82828. // All faces of the cube.
  82829. for (var face = 0; face < 6; face++) {
  82830. _loop_2(face);
  82831. }
  82832. };
  82833. for (var i = 0; i <= mipmapsCount; i++) {
  82834. _loop_1(i);
  82835. }
  82836. // Once all the textures haves been collected as RGBD stored in PNGs
  82837. return Promise.all(promises).then(function () {
  82838. // We can delete the hosting scene keeping track of all the creation objects
  82839. hostingScene.dispose();
  82840. // Creates the json header for the env texture
  82841. var info = {
  82842. version: 1,
  82843. width: cubeWidth,
  82844. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82845. specular: {
  82846. mipmaps: []
  82847. }
  82848. };
  82849. // Sets the specular image data information
  82850. var position = 0;
  82851. for (var i = 0; i <= mipmapsCount; i++) {
  82852. for (var face = 0; face < 6; face++) {
  82853. var byteLength = specularTextures[i * 6 + face].byteLength;
  82854. info.specular.mipmaps.push({
  82855. length: byteLength,
  82856. position: position
  82857. });
  82858. position += byteLength;
  82859. }
  82860. }
  82861. // Encode the JSON as an array buffer
  82862. var infoString = JSON.stringify(info);
  82863. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82864. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82865. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82866. infoView[i] = infoString.charCodeAt(i);
  82867. }
  82868. // Ends up with a null terminator for easier parsing
  82869. infoView[infoString.length] = 0x00;
  82870. // Computes the final required size and creates the storage
  82871. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82872. var finalBuffer = new ArrayBuffer(totalSize);
  82873. var finalBufferView = new Uint8Array(finalBuffer);
  82874. var dataView = new DataView(finalBuffer);
  82875. // Copy the magic bytes identifying the file in
  82876. var pos = 0;
  82877. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82878. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82879. }
  82880. // Add the json info
  82881. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82882. pos += infoBuffer.byteLength;
  82883. // Finally inserts the texture data
  82884. for (var i = 0; i <= mipmapsCount; i++) {
  82885. for (var face = 0; face < 6; face++) {
  82886. var dataBuffer = specularTextures[i * 6 + face];
  82887. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82888. pos += dataBuffer.byteLength;
  82889. }
  82890. }
  82891. // Voila
  82892. return finalBuffer;
  82893. });
  82894. };
  82895. /**
  82896. * Creates a JSON representation of the spherical data.
  82897. * @param texture defines the texture containing the polynomials
  82898. * @return the JSON representation of the spherical info
  82899. */
  82900. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82901. var polynmials = texture.sphericalPolynomial;
  82902. if (polynmials == null) {
  82903. return null;
  82904. }
  82905. return {
  82906. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82907. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82908. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82909. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82910. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82911. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82912. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82913. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82914. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82915. };
  82916. };
  82917. /**
  82918. * Uploads the texture info contained in the env file to the GPU.
  82919. * @param texture defines the internal texture to upload to
  82920. * @param arrayBuffer defines the buffer cotaining the data to load
  82921. * @param info defines the texture info retrieved through the GetEnvInfo method
  82922. * @returns a promise
  82923. */
  82924. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82925. if (info.version !== 1) {
  82926. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82927. }
  82928. var specularInfo = info.specular;
  82929. if (!specularInfo) {
  82930. // Nothing else parsed so far
  82931. return Promise.resolve();
  82932. }
  82933. // Double checks the enclosed info
  82934. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82935. mipmapsCount = Math.round(mipmapsCount) + 1;
  82936. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82937. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82938. }
  82939. var imageData = new Array(mipmapsCount);
  82940. for (var i = 0; i < mipmapsCount; i++) {
  82941. imageData[i] = new Array(6);
  82942. for (var face = 0; face < 6; face++) {
  82943. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82944. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82945. }
  82946. }
  82947. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82948. };
  82949. /**
  82950. * Uploads the levels of image data to the GPU.
  82951. * @param texture defines the internal texture to upload to
  82952. * @param imageData defines the array buffer views of image data [mipmap][face]
  82953. * @returns a promise
  82954. */
  82955. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82956. var mipmapsCount = imageData.length;
  82957. // Gets everything ready.
  82958. var engine = texture.getEngine();
  82959. var expandTexture = false;
  82960. var generateNonLODTextures = false;
  82961. var rgbdPostProcess = null;
  82962. var cubeRtt = null;
  82963. var lodTextures = null;
  82964. var caps = engine.getCaps();
  82965. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82966. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82967. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82968. // Add extra process if texture lod is not supported
  82969. if (!caps.textureLOD) {
  82970. expandTexture = false;
  82971. generateNonLODTextures = true;
  82972. lodTextures = {};
  82973. }
  82974. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82975. else if (engine.webGLVersion < 2) {
  82976. expandTexture = false;
  82977. }
  82978. // If half float available we can uncompress the texture
  82979. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82980. expandTexture = true;
  82981. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82982. }
  82983. // If full float available we can uncompress the texture
  82984. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82985. expandTexture = true;
  82986. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82987. }
  82988. // Expand the texture if possible
  82989. if (expandTexture) {
  82990. // Simply run through the decode PP
  82991. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82992. texture._isRGBD = false;
  82993. texture.invertY = false;
  82994. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82995. generateDepthBuffer: false,
  82996. generateMipMaps: true,
  82997. generateStencilBuffer: false,
  82998. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82999. type: texture.type,
  83000. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  83001. });
  83002. }
  83003. else {
  83004. texture._isRGBD = true;
  83005. texture.invertY = true;
  83006. // In case of missing support, applies the same patch than DDS files.
  83007. if (generateNonLODTextures) {
  83008. var mipSlices = 3;
  83009. var scale = texture._lodGenerationScale;
  83010. var offset = texture._lodGenerationOffset;
  83011. for (var i = 0; i < mipSlices; i++) {
  83012. //compute LOD from even spacing in smoothness (matching shader calculation)
  83013. var smoothness = i / (mipSlices - 1);
  83014. var roughness = 1 - smoothness;
  83015. var minLODIndex = offset; // roughness = 0
  83016. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  83017. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  83018. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  83019. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  83020. glTextureFromLod.isCube = true;
  83021. glTextureFromLod.invertY = true;
  83022. glTextureFromLod.generateMipMaps = false;
  83023. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  83024. // Wrap in a base texture for easy binding.
  83025. var lodTexture = new BABYLON.BaseTexture(null);
  83026. lodTexture.isCube = true;
  83027. lodTexture._texture = glTextureFromLod;
  83028. lodTextures[mipmapIndex] = lodTexture;
  83029. switch (i) {
  83030. case 0:
  83031. texture._lodTextureLow = lodTexture;
  83032. break;
  83033. case 1:
  83034. texture._lodTextureMid = lodTexture;
  83035. break;
  83036. case 2:
  83037. texture._lodTextureHigh = lodTexture;
  83038. break;
  83039. }
  83040. }
  83041. }
  83042. }
  83043. var promises = [];
  83044. var _loop_3 = function (i) {
  83045. var _loop_4 = function (face) {
  83046. // Constructs an image element from image data
  83047. var bytes = imageData[i][face];
  83048. var blob = new Blob([bytes], { type: 'image/png' });
  83049. var url = URL.createObjectURL(blob);
  83050. var image = new Image();
  83051. image.src = url;
  83052. // Enqueue promise to upload to the texture.
  83053. var promise = new Promise(function (resolve, reject) {
  83054. image.onload = function () {
  83055. if (expandTexture) {
  83056. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83057. reject(message);
  83058. }, image);
  83059. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83060. // Uncompress the data to a RTT
  83061. rgbdPostProcess.onApply = function (effect) {
  83062. effect._bindTexture("textureSampler", tempTexture_1);
  83063. effect.setFloat2("scale", 1, 1);
  83064. };
  83065. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83066. // Cleanup
  83067. engine.restoreDefaultFramebuffer();
  83068. tempTexture_1.dispose();
  83069. window.URL.revokeObjectURL(url);
  83070. resolve();
  83071. });
  83072. }
  83073. else {
  83074. engine._uploadImageToTexture(texture, face, i, image);
  83075. // Upload the face to the none lod texture support
  83076. if (generateNonLODTextures) {
  83077. var lodTexture = lodTextures[i];
  83078. if (lodTexture) {
  83079. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  83080. }
  83081. }
  83082. resolve();
  83083. }
  83084. };
  83085. image.onerror = function (error) {
  83086. reject(error);
  83087. };
  83088. });
  83089. promises.push(promise);
  83090. };
  83091. // All faces
  83092. for (var face = 0; face < 6; face++) {
  83093. _loop_4(face);
  83094. }
  83095. };
  83096. // All mipmaps
  83097. for (var i = 0; i < mipmapsCount; i++) {
  83098. _loop_3(i);
  83099. }
  83100. // Once all done, finishes the cleanup and return
  83101. return Promise.all(promises).then(function () {
  83102. // Relase temp RTT.
  83103. if (cubeRtt) {
  83104. engine._releaseFramebufferObjects(cubeRtt);
  83105. cubeRtt._swapAndDie(texture);
  83106. }
  83107. // Relase temp Post Process.
  83108. if (rgbdPostProcess) {
  83109. rgbdPostProcess.dispose();
  83110. }
  83111. // Flag internal texture as ready in case they are in use.
  83112. if (generateNonLODTextures) {
  83113. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83114. texture._lodTextureHigh._texture.isReady = true;
  83115. }
  83116. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83117. texture._lodTextureMid._texture.isReady = true;
  83118. }
  83119. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83120. texture._lodTextureLow._texture.isReady = true;
  83121. }
  83122. }
  83123. });
  83124. };
  83125. /**
  83126. * Uploads spherical polynomials information to the texture.
  83127. * @param texture defines the texture we are trying to upload the information to
  83128. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83129. */
  83130. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83131. if (info.version !== 1) {
  83132. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83133. }
  83134. var irradianceInfo = info.irradiance;
  83135. if (!irradianceInfo) {
  83136. return;
  83137. }
  83138. var sp = new BABYLON.SphericalPolynomial();
  83139. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83140. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83141. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83142. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83143. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83144. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83145. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83146. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83147. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83148. texture._sphericalPolynomial = sp;
  83149. };
  83150. /**
  83151. * Magic number identifying the env file.
  83152. */
  83153. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83154. return EnvironmentTextureTools;
  83155. }());
  83156. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83157. })(BABYLON || (BABYLON = {}));
  83158. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83159. var BABYLON;
  83160. (function (BABYLON) {
  83161. /**
  83162. * This represents a texture coming from an HDR input.
  83163. *
  83164. * The only supported format is currently panorama picture stored in RGBE format.
  83165. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83166. */
  83167. var HDRCubeTexture = /** @class */ (function (_super) {
  83168. __extends(HDRCubeTexture, _super);
  83169. /**
  83170. * Instantiates an HDRTexture from the following parameters.
  83171. *
  83172. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83173. * @param scene The scene the texture will be used in
  83174. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83175. * @param noMipmap Forces to not generate the mipmap if true
  83176. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83177. * @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)
  83178. * @param reserved Reserved flag for internal use.
  83179. */
  83180. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83181. if (noMipmap === void 0) { noMipmap = false; }
  83182. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83183. if (gammaSpace === void 0) { gammaSpace = false; }
  83184. if (reserved === void 0) { reserved = false; }
  83185. if (onLoad === void 0) { onLoad = null; }
  83186. if (onError === void 0) { onError = null; }
  83187. var _this = _super.call(this, scene) || this;
  83188. _this._generateHarmonics = true;
  83189. _this._onLoad = null;
  83190. _this._onError = null;
  83191. /**
  83192. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83193. */
  83194. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83195. _this._isBlocking = true;
  83196. _this._rotationY = 0;
  83197. /**
  83198. * Gets or sets the center of the bounding box associated with the cube texture
  83199. * It must define where the camera used to render the texture was set
  83200. */
  83201. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83202. if (!url) {
  83203. return _this;
  83204. }
  83205. _this.name = url;
  83206. _this.url = url;
  83207. _this.hasAlpha = false;
  83208. _this.isCube = true;
  83209. _this._textureMatrix = BABYLON.Matrix.Identity();
  83210. _this._onLoad = onLoad;
  83211. _this._onError = onError;
  83212. _this.gammaSpace = gammaSpace;
  83213. _this._noMipmap = noMipmap;
  83214. _this._size = size;
  83215. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83216. if (!_this._texture) {
  83217. if (!scene.useDelayedTextureLoading) {
  83218. _this.loadTexture();
  83219. }
  83220. else {
  83221. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83222. }
  83223. }
  83224. return _this;
  83225. }
  83226. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83227. /**
  83228. * Gets wether or not the texture is blocking during loading.
  83229. */
  83230. get: function () {
  83231. return this._isBlocking;
  83232. },
  83233. /**
  83234. * Sets wether or not the texture is blocking during loading.
  83235. */
  83236. set: function (value) {
  83237. this._isBlocking = value;
  83238. },
  83239. enumerable: true,
  83240. configurable: true
  83241. });
  83242. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83243. /**
  83244. * Gets texture matrix rotation angle around Y axis radians.
  83245. */
  83246. get: function () {
  83247. return this._rotationY;
  83248. },
  83249. /**
  83250. * Sets texture matrix rotation angle around Y axis in radians.
  83251. */
  83252. set: function (value) {
  83253. this._rotationY = value;
  83254. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83255. },
  83256. enumerable: true,
  83257. configurable: true
  83258. });
  83259. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83260. get: function () {
  83261. return this._boundingBoxSize;
  83262. },
  83263. /**
  83264. * Gets or sets the size of the bounding box associated with the cube texture
  83265. * When defined, the cubemap will switch to local mode
  83266. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83267. * @example https://www.babylonjs-playground.com/#RNASML
  83268. */
  83269. set: function (value) {
  83270. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83271. return;
  83272. }
  83273. this._boundingBoxSize = value;
  83274. var scene = this.getScene();
  83275. if (scene) {
  83276. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83277. }
  83278. },
  83279. enumerable: true,
  83280. configurable: true
  83281. });
  83282. /**
  83283. * Occurs when the file is raw .hdr file.
  83284. */
  83285. HDRCubeTexture.prototype.loadTexture = function () {
  83286. var _this = this;
  83287. var callback = function (buffer) {
  83288. _this.lodGenerationOffset = 0.0;
  83289. _this.lodGenerationScale = 0.8;
  83290. var scene = _this.getScene();
  83291. if (!scene) {
  83292. return null;
  83293. }
  83294. // Extract the raw linear data.
  83295. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83296. // Generate harmonics if needed.
  83297. if (_this._generateHarmonics) {
  83298. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83299. _this.sphericalPolynomial = sphericalPolynomial;
  83300. }
  83301. var results = [];
  83302. var byteArray = null;
  83303. // Push each faces.
  83304. for (var j = 0; j < 6; j++) {
  83305. // Create uintarray fallback.
  83306. if (!scene.getEngine().getCaps().textureFloat) {
  83307. // 3 channels of 1 bytes per pixel in bytes.
  83308. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83309. byteArray = new Uint8Array(byteBuffer);
  83310. }
  83311. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83312. // If special cases.
  83313. if (_this.gammaSpace || byteArray) {
  83314. for (var i = 0; i < _this._size * _this._size; i++) {
  83315. // Put in gamma space if requested.
  83316. if (_this.gammaSpace) {
  83317. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83318. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83319. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83320. }
  83321. // Convert to int texture for fallback.
  83322. if (byteArray) {
  83323. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83324. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83325. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83326. // May use luminance instead if the result is not accurate.
  83327. var max = Math.max(Math.max(r, g), b);
  83328. if (max > 255) {
  83329. var scale = 255 / max;
  83330. r *= scale;
  83331. g *= scale;
  83332. b *= scale;
  83333. }
  83334. byteArray[(i * 3) + 0] = r;
  83335. byteArray[(i * 3) + 1] = g;
  83336. byteArray[(i * 3) + 2] = b;
  83337. }
  83338. }
  83339. }
  83340. if (byteArray) {
  83341. results.push(byteArray);
  83342. }
  83343. else {
  83344. results.push(dataFace);
  83345. }
  83346. }
  83347. return results;
  83348. };
  83349. var scene = this.getScene();
  83350. if (scene) {
  83351. 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);
  83352. }
  83353. };
  83354. HDRCubeTexture.prototype.clone = function () {
  83355. var scene = this.getScene();
  83356. if (!scene) {
  83357. return this;
  83358. }
  83359. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83360. // Base texture
  83361. newTexture.level = this.level;
  83362. newTexture.wrapU = this.wrapU;
  83363. newTexture.wrapV = this.wrapV;
  83364. newTexture.coordinatesIndex = this.coordinatesIndex;
  83365. newTexture.coordinatesMode = this.coordinatesMode;
  83366. return newTexture;
  83367. };
  83368. // Methods
  83369. HDRCubeTexture.prototype.delayLoad = function () {
  83370. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83371. return;
  83372. }
  83373. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83374. this._texture = this._getFromCache(this.url, this._noMipmap);
  83375. if (!this._texture) {
  83376. this.loadTexture();
  83377. }
  83378. };
  83379. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83380. return this._textureMatrix;
  83381. };
  83382. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83383. this._textureMatrix = value;
  83384. };
  83385. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83386. var texture = null;
  83387. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83388. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83389. texture.name = parsedTexture.name;
  83390. texture.hasAlpha = parsedTexture.hasAlpha;
  83391. texture.level = parsedTexture.level;
  83392. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83393. texture.isBlocking = parsedTexture.isBlocking;
  83394. }
  83395. if (texture) {
  83396. if (parsedTexture.boundingBoxPosition) {
  83397. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83398. }
  83399. if (parsedTexture.boundingBoxSize) {
  83400. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83401. }
  83402. if (parsedTexture.rotationY) {
  83403. texture.rotationY = parsedTexture.rotationY;
  83404. }
  83405. }
  83406. return texture;
  83407. };
  83408. HDRCubeTexture.prototype.serialize = function () {
  83409. if (!this.name) {
  83410. return null;
  83411. }
  83412. var serializationObject = {};
  83413. serializationObject.name = this.name;
  83414. serializationObject.hasAlpha = this.hasAlpha;
  83415. serializationObject.isCube = true;
  83416. serializationObject.level = this.level;
  83417. serializationObject.size = this._size;
  83418. serializationObject.coordinatesMode = this.coordinatesMode;
  83419. serializationObject.useInGammaSpace = this.gammaSpace;
  83420. serializationObject.generateHarmonics = this._generateHarmonics;
  83421. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83422. serializationObject.noMipmap = this._noMipmap;
  83423. serializationObject.isBlocking = this._isBlocking;
  83424. serializationObject.rotationY = this._rotationY;
  83425. return serializationObject;
  83426. };
  83427. HDRCubeTexture._facesMapping = [
  83428. "right",
  83429. "left",
  83430. "up",
  83431. "down",
  83432. "front",
  83433. "back"
  83434. ];
  83435. return HDRCubeTexture;
  83436. }(BABYLON.BaseTexture));
  83437. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83438. })(BABYLON || (BABYLON = {}));
  83439. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83440. var BABYLON;
  83441. (function (BABYLON) {
  83442. var IndexedVector2 = /** @class */ (function (_super) {
  83443. __extends(IndexedVector2, _super);
  83444. function IndexedVector2(original, index) {
  83445. var _this = _super.call(this, original.x, original.y) || this;
  83446. _this.index = index;
  83447. return _this;
  83448. }
  83449. return IndexedVector2;
  83450. }(BABYLON.Vector2));
  83451. var PolygonPoints = /** @class */ (function () {
  83452. function PolygonPoints() {
  83453. this.elements = new Array();
  83454. }
  83455. PolygonPoints.prototype.add = function (originalPoints) {
  83456. var _this = this;
  83457. var result = new Array();
  83458. originalPoints.forEach(function (point) {
  83459. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83460. var newPoint = new IndexedVector2(point, _this.elements.length);
  83461. result.push(newPoint);
  83462. _this.elements.push(newPoint);
  83463. }
  83464. });
  83465. return result;
  83466. };
  83467. PolygonPoints.prototype.computeBounds = function () {
  83468. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83469. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83470. this.elements.forEach(function (point) {
  83471. // x
  83472. if (point.x < lmin.x) {
  83473. lmin.x = point.x;
  83474. }
  83475. else if (point.x > lmax.x) {
  83476. lmax.x = point.x;
  83477. }
  83478. // y
  83479. if (point.y < lmin.y) {
  83480. lmin.y = point.y;
  83481. }
  83482. else if (point.y > lmax.y) {
  83483. lmax.y = point.y;
  83484. }
  83485. });
  83486. return {
  83487. min: lmin,
  83488. max: lmax,
  83489. width: lmax.x - lmin.x,
  83490. height: lmax.y - lmin.y
  83491. };
  83492. };
  83493. return PolygonPoints;
  83494. }());
  83495. var Polygon = /** @class */ (function () {
  83496. function Polygon() {
  83497. }
  83498. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83499. return [
  83500. new BABYLON.Vector2(xmin, ymin),
  83501. new BABYLON.Vector2(xmax, ymin),
  83502. new BABYLON.Vector2(xmax, ymax),
  83503. new BABYLON.Vector2(xmin, ymax)
  83504. ];
  83505. };
  83506. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83507. if (cx === void 0) { cx = 0; }
  83508. if (cy === void 0) { cy = 0; }
  83509. if (numberOfSides === void 0) { numberOfSides = 32; }
  83510. var result = new Array();
  83511. var angle = 0;
  83512. var increment = (Math.PI * 2) / numberOfSides;
  83513. for (var i = 0; i < numberOfSides; i++) {
  83514. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83515. angle -= increment;
  83516. }
  83517. return result;
  83518. };
  83519. Polygon.Parse = function (input) {
  83520. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83521. var i, result = [];
  83522. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83523. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83524. }
  83525. return result;
  83526. };
  83527. Polygon.StartingAt = function (x, y) {
  83528. return BABYLON.Path2.StartingAt(x, y);
  83529. };
  83530. return Polygon;
  83531. }());
  83532. BABYLON.Polygon = Polygon;
  83533. var PolygonMeshBuilder = /** @class */ (function () {
  83534. function PolygonMeshBuilder(name, contours, scene) {
  83535. this._points = new PolygonPoints();
  83536. this._outlinepoints = new PolygonPoints();
  83537. this._holes = new Array();
  83538. this._epoints = new Array();
  83539. this._eholes = new Array();
  83540. this._name = name;
  83541. this._scene = scene;
  83542. var points;
  83543. if (contours instanceof BABYLON.Path2) {
  83544. points = contours.getPoints();
  83545. }
  83546. else {
  83547. points = contours;
  83548. }
  83549. this._addToepoint(points);
  83550. this._points.add(points);
  83551. this._outlinepoints.add(points);
  83552. if (typeof earcut === 'undefined') {
  83553. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83554. }
  83555. }
  83556. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83557. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83558. var p = points_1[_i];
  83559. this._epoints.push(p.x, p.y);
  83560. }
  83561. };
  83562. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83563. this._points.add(hole);
  83564. var holepoints = new PolygonPoints();
  83565. holepoints.add(hole);
  83566. this._holes.push(holepoints);
  83567. this._eholes.push(this._epoints.length / 2);
  83568. this._addToepoint(hole);
  83569. return this;
  83570. };
  83571. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83572. var _this = this;
  83573. if (updatable === void 0) { updatable = false; }
  83574. if (depth === void 0) { depth = 0; }
  83575. var result = new BABYLON.Mesh(this._name, this._scene);
  83576. var normals = new Array();
  83577. var positions = new Array();
  83578. var uvs = new Array();
  83579. var bounds = this._points.computeBounds();
  83580. this._points.elements.forEach(function (p) {
  83581. normals.push(0, 1.0, 0);
  83582. positions.push(p.x, 0, p.y);
  83583. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83584. });
  83585. var indices = new Array();
  83586. var res = earcut(this._epoints, this._eholes, 2);
  83587. for (var i = 0; i < res.length; i++) {
  83588. indices.push(res[i]);
  83589. }
  83590. if (depth > 0) {
  83591. var positionscount = (positions.length / 3); //get the current pointcount
  83592. this._points.elements.forEach(function (p) {
  83593. normals.push(0, -1.0, 0);
  83594. positions.push(p.x, -depth, p.y);
  83595. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83596. });
  83597. var totalCount = indices.length;
  83598. for (var i = 0; i < totalCount; i += 3) {
  83599. var i0 = indices[i + 0];
  83600. var i1 = indices[i + 1];
  83601. var i2 = indices[i + 2];
  83602. indices.push(i2 + positionscount);
  83603. indices.push(i1 + positionscount);
  83604. indices.push(i0 + positionscount);
  83605. }
  83606. //Add the sides
  83607. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83608. this._holes.forEach(function (hole) {
  83609. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83610. });
  83611. }
  83612. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83613. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83614. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83615. result.setIndices(indices);
  83616. return result;
  83617. };
  83618. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83619. var StartIndex = positions.length / 3;
  83620. var ulength = 0;
  83621. for (var i = 0; i < points.elements.length; i++) {
  83622. var p = points.elements[i];
  83623. var p1;
  83624. if ((i + 1) > points.elements.length - 1) {
  83625. p1 = points.elements[0];
  83626. }
  83627. else {
  83628. p1 = points.elements[i + 1];
  83629. }
  83630. positions.push(p.x, 0, p.y);
  83631. positions.push(p.x, -depth, p.y);
  83632. positions.push(p1.x, 0, p1.y);
  83633. positions.push(p1.x, -depth, p1.y);
  83634. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83635. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83636. var v3 = v2.subtract(v1);
  83637. var v4 = new BABYLON.Vector3(0, 1, 0);
  83638. var vn = BABYLON.Vector3.Cross(v3, v4);
  83639. vn = vn.normalize();
  83640. uvs.push(ulength / bounds.width, 0);
  83641. uvs.push(ulength / bounds.width, 1);
  83642. ulength += v3.length();
  83643. uvs.push((ulength / bounds.width), 0);
  83644. uvs.push((ulength / bounds.width), 1);
  83645. if (!flip) {
  83646. normals.push(-vn.x, -vn.y, -vn.z);
  83647. normals.push(-vn.x, -vn.y, -vn.z);
  83648. normals.push(-vn.x, -vn.y, -vn.z);
  83649. normals.push(-vn.x, -vn.y, -vn.z);
  83650. indices.push(StartIndex);
  83651. indices.push(StartIndex + 1);
  83652. indices.push(StartIndex + 2);
  83653. indices.push(StartIndex + 1);
  83654. indices.push(StartIndex + 3);
  83655. indices.push(StartIndex + 2);
  83656. }
  83657. else {
  83658. normals.push(vn.x, vn.y, vn.z);
  83659. normals.push(vn.x, vn.y, vn.z);
  83660. normals.push(vn.x, vn.y, vn.z);
  83661. normals.push(vn.x, vn.y, vn.z);
  83662. indices.push(StartIndex);
  83663. indices.push(StartIndex + 2);
  83664. indices.push(StartIndex + 1);
  83665. indices.push(StartIndex + 1);
  83666. indices.push(StartIndex + 2);
  83667. indices.push(StartIndex + 3);
  83668. }
  83669. StartIndex += 4;
  83670. }
  83671. ;
  83672. };
  83673. return PolygonMeshBuilder;
  83674. }());
  83675. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83676. })(BABYLON || (BABYLON = {}));
  83677. //# sourceMappingURL=babylon.polygonMesh.js.map
  83678. var BABYLON;
  83679. (function (BABYLON) {
  83680. // Unique ID when we import meshes from Babylon to CSG
  83681. var currentCSGMeshId = 0;
  83682. // # class Vertex
  83683. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83684. // one to provide additional features like texture coordinates and vertex
  83685. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83686. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83687. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83688. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83689. // is not used anywhere else.
  83690. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83691. var Vertex = /** @class */ (function () {
  83692. function Vertex(pos, normal, uv) {
  83693. this.pos = pos;
  83694. this.normal = normal;
  83695. this.uv = uv;
  83696. }
  83697. Vertex.prototype.clone = function () {
  83698. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83699. };
  83700. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83701. // orientation of a polygon is flipped.
  83702. Vertex.prototype.flip = function () {
  83703. this.normal = this.normal.scale(-1);
  83704. };
  83705. // Create a new vertex between this vertex and `other` by linearly
  83706. // interpolating all properties using a parameter of `t`. Subclasses should
  83707. // override this to interpolate additional properties.
  83708. Vertex.prototype.interpolate = function (other, t) {
  83709. 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));
  83710. };
  83711. return Vertex;
  83712. }());
  83713. // # class Plane
  83714. // Represents a plane in 3D space.
  83715. var Plane = /** @class */ (function () {
  83716. function Plane(normal, w) {
  83717. this.normal = normal;
  83718. this.w = w;
  83719. }
  83720. Plane.FromPoints = function (a, b, c) {
  83721. var v0 = c.subtract(a);
  83722. var v1 = b.subtract(a);
  83723. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83724. return null;
  83725. }
  83726. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83727. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83728. };
  83729. Plane.prototype.clone = function () {
  83730. return new Plane(this.normal.clone(), this.w);
  83731. };
  83732. Plane.prototype.flip = function () {
  83733. this.normal.scaleInPlace(-1);
  83734. this.w = -this.w;
  83735. };
  83736. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83737. // fragments in the appropriate lists. Coplanar polygons go into either
  83738. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83739. // respect to this plane. Polygons in front or in back of this plane go into
  83740. // either `front` or `back`.
  83741. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83742. var COPLANAR = 0;
  83743. var FRONT = 1;
  83744. var BACK = 2;
  83745. var SPANNING = 3;
  83746. // Classify each point as well as the entire polygon into one of the above
  83747. // four classes.
  83748. var polygonType = 0;
  83749. var types = [];
  83750. var i;
  83751. var t;
  83752. for (i = 0; i < polygon.vertices.length; i++) {
  83753. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83754. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83755. polygonType |= type;
  83756. types.push(type);
  83757. }
  83758. // Put the polygon in the correct list, splitting it when necessary.
  83759. switch (polygonType) {
  83760. case COPLANAR:
  83761. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83762. break;
  83763. case FRONT:
  83764. front.push(polygon);
  83765. break;
  83766. case BACK:
  83767. back.push(polygon);
  83768. break;
  83769. case SPANNING:
  83770. var f = [], b = [];
  83771. for (i = 0; i < polygon.vertices.length; i++) {
  83772. var j = (i + 1) % polygon.vertices.length;
  83773. var ti = types[i], tj = types[j];
  83774. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83775. if (ti !== BACK)
  83776. f.push(vi);
  83777. if (ti !== FRONT)
  83778. b.push(ti !== BACK ? vi.clone() : vi);
  83779. if ((ti | tj) === SPANNING) {
  83780. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83781. var v = vi.interpolate(vj, t);
  83782. f.push(v);
  83783. b.push(v.clone());
  83784. }
  83785. }
  83786. var poly;
  83787. if (f.length >= 3) {
  83788. poly = new Polygon(f, polygon.shared);
  83789. if (poly.plane)
  83790. front.push(poly);
  83791. }
  83792. if (b.length >= 3) {
  83793. poly = new Polygon(b, polygon.shared);
  83794. if (poly.plane)
  83795. back.push(poly);
  83796. }
  83797. break;
  83798. }
  83799. };
  83800. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83801. // point is on the plane.
  83802. Plane.EPSILON = 1e-5;
  83803. return Plane;
  83804. }());
  83805. // # class Polygon
  83806. // Represents a convex polygon. The vertices used to initialize a polygon must
  83807. // be coplanar and form a convex loop.
  83808. //
  83809. // Each convex polygon has a `shared` property, which is shared between all
  83810. // polygons that are clones of each other or were split from the same polygon.
  83811. // This can be used to define per-polygon properties (such as surface color).
  83812. var Polygon = /** @class */ (function () {
  83813. function Polygon(vertices, shared) {
  83814. this.vertices = vertices;
  83815. this.shared = shared;
  83816. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83817. }
  83818. Polygon.prototype.clone = function () {
  83819. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83820. return new Polygon(vertices, this.shared);
  83821. };
  83822. Polygon.prototype.flip = function () {
  83823. this.vertices.reverse().map(function (v) { v.flip(); });
  83824. this.plane.flip();
  83825. };
  83826. return Polygon;
  83827. }());
  83828. // # class Node
  83829. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83830. // by picking a polygon to split along. That polygon (and all other coplanar
  83831. // polygons) are added directly to that node and the other polygons are added to
  83832. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83833. // no distinction between internal and leaf nodes.
  83834. var Node = /** @class */ (function () {
  83835. function Node(polygons) {
  83836. this.plane = null;
  83837. this.front = null;
  83838. this.back = null;
  83839. this.polygons = new Array();
  83840. if (polygons) {
  83841. this.build(polygons);
  83842. }
  83843. }
  83844. Node.prototype.clone = function () {
  83845. var node = new Node();
  83846. node.plane = this.plane && this.plane.clone();
  83847. node.front = this.front && this.front.clone();
  83848. node.back = this.back && this.back.clone();
  83849. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83850. return node;
  83851. };
  83852. // Convert solid space to empty space and empty space to solid space.
  83853. Node.prototype.invert = function () {
  83854. for (var i = 0; i < this.polygons.length; i++) {
  83855. this.polygons[i].flip();
  83856. }
  83857. if (this.plane) {
  83858. this.plane.flip();
  83859. }
  83860. if (this.front) {
  83861. this.front.invert();
  83862. }
  83863. if (this.back) {
  83864. this.back.invert();
  83865. }
  83866. var temp = this.front;
  83867. this.front = this.back;
  83868. this.back = temp;
  83869. };
  83870. // Recursively remove all polygons in `polygons` that are inside this BSP
  83871. // tree.
  83872. Node.prototype.clipPolygons = function (polygons) {
  83873. if (!this.plane)
  83874. return polygons.slice();
  83875. var front = new Array(), back = new Array();
  83876. for (var i = 0; i < polygons.length; i++) {
  83877. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83878. }
  83879. if (this.front) {
  83880. front = this.front.clipPolygons(front);
  83881. }
  83882. if (this.back) {
  83883. back = this.back.clipPolygons(back);
  83884. }
  83885. else {
  83886. back = [];
  83887. }
  83888. return front.concat(back);
  83889. };
  83890. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83891. // `bsp`.
  83892. Node.prototype.clipTo = function (bsp) {
  83893. this.polygons = bsp.clipPolygons(this.polygons);
  83894. if (this.front)
  83895. this.front.clipTo(bsp);
  83896. if (this.back)
  83897. this.back.clipTo(bsp);
  83898. };
  83899. // Return a list of all polygons in this BSP tree.
  83900. Node.prototype.allPolygons = function () {
  83901. var polygons = this.polygons.slice();
  83902. if (this.front)
  83903. polygons = polygons.concat(this.front.allPolygons());
  83904. if (this.back)
  83905. polygons = polygons.concat(this.back.allPolygons());
  83906. return polygons;
  83907. };
  83908. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83909. // new polygons are filtered down to the bottom of the tree and become new
  83910. // nodes there. Each set of polygons is partitioned using the first polygon
  83911. // (no heuristic is used to pick a good split).
  83912. Node.prototype.build = function (polygons) {
  83913. if (!polygons.length)
  83914. return;
  83915. if (!this.plane)
  83916. this.plane = polygons[0].plane.clone();
  83917. var front = new Array(), back = new Array();
  83918. for (var i = 0; i < polygons.length; i++) {
  83919. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83920. }
  83921. if (front.length) {
  83922. if (!this.front)
  83923. this.front = new Node();
  83924. this.front.build(front);
  83925. }
  83926. if (back.length) {
  83927. if (!this.back)
  83928. this.back = new Node();
  83929. this.back.build(back);
  83930. }
  83931. };
  83932. return Node;
  83933. }());
  83934. var CSG = /** @class */ (function () {
  83935. function CSG() {
  83936. this.polygons = new Array();
  83937. }
  83938. // Convert BABYLON.Mesh to BABYLON.CSG
  83939. CSG.FromMesh = function (mesh) {
  83940. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83941. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83942. if (mesh instanceof BABYLON.Mesh) {
  83943. mesh.computeWorldMatrix(true);
  83944. matrix = mesh.getWorldMatrix();
  83945. meshPosition = mesh.position.clone();
  83946. meshRotation = mesh.rotation.clone();
  83947. if (mesh.rotationQuaternion) {
  83948. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83949. }
  83950. meshScaling = mesh.scaling.clone();
  83951. }
  83952. else {
  83953. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83954. }
  83955. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83956. var subMeshes = mesh.subMeshes;
  83957. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83958. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83959. vertices = [];
  83960. for (var j = 0; j < 3; j++) {
  83961. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83962. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83963. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83964. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83965. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83966. vertex = new Vertex(position, normal, uv);
  83967. vertices.push(vertex);
  83968. }
  83969. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83970. // To handle the case of degenerated triangle
  83971. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83972. if (polygon.plane)
  83973. polygons.push(polygon);
  83974. }
  83975. }
  83976. var csg = CSG.FromPolygons(polygons);
  83977. csg.matrix = matrix;
  83978. csg.position = meshPosition;
  83979. csg.rotation = meshRotation;
  83980. csg.scaling = meshScaling;
  83981. csg.rotationQuaternion = meshRotationQuaternion;
  83982. currentCSGMeshId++;
  83983. return csg;
  83984. };
  83985. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83986. CSG.FromPolygons = function (polygons) {
  83987. var csg = new CSG();
  83988. csg.polygons = polygons;
  83989. return csg;
  83990. };
  83991. CSG.prototype.clone = function () {
  83992. var csg = new CSG();
  83993. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83994. csg.copyTransformAttributes(this);
  83995. return csg;
  83996. };
  83997. CSG.prototype.union = function (csg) {
  83998. var a = new Node(this.clone().polygons);
  83999. var b = new Node(csg.clone().polygons);
  84000. a.clipTo(b);
  84001. b.clipTo(a);
  84002. b.invert();
  84003. b.clipTo(a);
  84004. b.invert();
  84005. a.build(b.allPolygons());
  84006. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84007. };
  84008. CSG.prototype.unionInPlace = function (csg) {
  84009. var a = new Node(this.polygons);
  84010. var b = new Node(csg.polygons);
  84011. a.clipTo(b);
  84012. b.clipTo(a);
  84013. b.invert();
  84014. b.clipTo(a);
  84015. b.invert();
  84016. a.build(b.allPolygons());
  84017. this.polygons = a.allPolygons();
  84018. };
  84019. CSG.prototype.subtract = function (csg) {
  84020. var a = new Node(this.clone().polygons);
  84021. var b = new Node(csg.clone().polygons);
  84022. a.invert();
  84023. a.clipTo(b);
  84024. b.clipTo(a);
  84025. b.invert();
  84026. b.clipTo(a);
  84027. b.invert();
  84028. a.build(b.allPolygons());
  84029. a.invert();
  84030. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84031. };
  84032. CSG.prototype.subtractInPlace = function (csg) {
  84033. var a = new Node(this.polygons);
  84034. var b = new Node(csg.polygons);
  84035. a.invert();
  84036. a.clipTo(b);
  84037. b.clipTo(a);
  84038. b.invert();
  84039. b.clipTo(a);
  84040. b.invert();
  84041. a.build(b.allPolygons());
  84042. a.invert();
  84043. this.polygons = a.allPolygons();
  84044. };
  84045. CSG.prototype.intersect = function (csg) {
  84046. var a = new Node(this.clone().polygons);
  84047. var b = new Node(csg.clone().polygons);
  84048. a.invert();
  84049. b.clipTo(a);
  84050. b.invert();
  84051. a.clipTo(b);
  84052. b.clipTo(a);
  84053. a.build(b.allPolygons());
  84054. a.invert();
  84055. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84056. };
  84057. CSG.prototype.intersectInPlace = function (csg) {
  84058. var a = new Node(this.polygons);
  84059. var b = new Node(csg.polygons);
  84060. a.invert();
  84061. b.clipTo(a);
  84062. b.invert();
  84063. a.clipTo(b);
  84064. b.clipTo(a);
  84065. a.build(b.allPolygons());
  84066. a.invert();
  84067. this.polygons = a.allPolygons();
  84068. };
  84069. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84070. // not modified.
  84071. CSG.prototype.inverse = function () {
  84072. var csg = this.clone();
  84073. csg.inverseInPlace();
  84074. return csg;
  84075. };
  84076. CSG.prototype.inverseInPlace = function () {
  84077. this.polygons.map(function (p) { p.flip(); });
  84078. };
  84079. // This is used to keep meshes transformations so they can be restored
  84080. // when we build back a Babylon Mesh
  84081. // NB : All CSG operations are performed in world coordinates
  84082. CSG.prototype.copyTransformAttributes = function (csg) {
  84083. this.matrix = csg.matrix;
  84084. this.position = csg.position;
  84085. this.rotation = csg.rotation;
  84086. this.scaling = csg.scaling;
  84087. this.rotationQuaternion = csg.rotationQuaternion;
  84088. return this;
  84089. };
  84090. // Build Raw mesh from CSG
  84091. // Coordinates here are in world space
  84092. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84093. var matrix = this.matrix.clone();
  84094. matrix.invert();
  84095. 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;
  84096. if (keepSubMeshes) {
  84097. // Sort Polygons, since subMeshes are indices range
  84098. polygons.sort(function (a, b) {
  84099. if (a.shared.meshId === b.shared.meshId) {
  84100. return a.shared.subMeshId - b.shared.subMeshId;
  84101. }
  84102. else {
  84103. return a.shared.meshId - b.shared.meshId;
  84104. }
  84105. });
  84106. }
  84107. for (var i = 0, il = polygons.length; i < il; i++) {
  84108. polygon = polygons[i];
  84109. // Building SubMeshes
  84110. if (!subMesh_dict[polygon.shared.meshId]) {
  84111. subMesh_dict[polygon.shared.meshId] = {};
  84112. }
  84113. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84114. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84115. indexStart: +Infinity,
  84116. indexEnd: -Infinity,
  84117. materialIndex: polygon.shared.materialIndex
  84118. };
  84119. }
  84120. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84121. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84122. polygonIndices[0] = 0;
  84123. polygonIndices[1] = j - 1;
  84124. polygonIndices[2] = j;
  84125. for (var k = 0; k < 3; k++) {
  84126. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84127. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84128. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84129. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84130. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84131. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84132. // Check if 2 points can be merged
  84133. if (!(typeof vertex_idx !== 'undefined' &&
  84134. normals[vertex_idx * 3] === localNormal.x &&
  84135. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84136. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84137. uvs[vertex_idx * 2] === uv.x &&
  84138. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84139. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84140. uvs.push(uv.x, uv.y);
  84141. normals.push(normal.x, normal.y, normal.z);
  84142. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84143. }
  84144. indices.push(vertex_idx);
  84145. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84146. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84147. currentIndex++;
  84148. }
  84149. }
  84150. }
  84151. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84152. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84153. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84154. mesh.setIndices(indices, null);
  84155. if (keepSubMeshes) {
  84156. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84157. var materialIndexOffset = 0, materialMaxIndex;
  84158. mesh.subMeshes = new Array();
  84159. for (var m in subMesh_dict) {
  84160. materialMaxIndex = -1;
  84161. for (var sm in subMesh_dict[m]) {
  84162. subMesh_obj = subMesh_dict[m][sm];
  84163. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84164. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84165. }
  84166. materialIndexOffset += ++materialMaxIndex;
  84167. }
  84168. }
  84169. return mesh;
  84170. };
  84171. // Build Mesh from CSG taking material and transforms into account
  84172. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84173. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84174. mesh.material = material;
  84175. mesh.position.copyFrom(this.position);
  84176. mesh.rotation.copyFrom(this.rotation);
  84177. if (this.rotationQuaternion) {
  84178. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84179. }
  84180. mesh.scaling.copyFrom(this.scaling);
  84181. mesh.computeWorldMatrix(true);
  84182. return mesh;
  84183. };
  84184. return CSG;
  84185. }());
  84186. BABYLON.CSG = CSG;
  84187. })(BABYLON || (BABYLON = {}));
  84188. //# sourceMappingURL=babylon.csg.js.map
  84189. var BABYLON;
  84190. (function (BABYLON) {
  84191. var LensFlare = /** @class */ (function () {
  84192. function LensFlare(size, position, color, imgUrl, system) {
  84193. this.size = size;
  84194. this.position = position;
  84195. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84196. this.color = color || new BABYLON.Color3(1, 1, 1);
  84197. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84198. this._system = system;
  84199. system.lensFlares.push(this);
  84200. }
  84201. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84202. return new LensFlare(size, position, color, imgUrl, system);
  84203. };
  84204. LensFlare.prototype.dispose = function () {
  84205. if (this.texture) {
  84206. this.texture.dispose();
  84207. }
  84208. // Remove from scene
  84209. var index = this._system.lensFlares.indexOf(this);
  84210. this._system.lensFlares.splice(index, 1);
  84211. };
  84212. ;
  84213. return LensFlare;
  84214. }());
  84215. BABYLON.LensFlare = LensFlare;
  84216. })(BABYLON || (BABYLON = {}));
  84217. //# sourceMappingURL=babylon.lensFlare.js.map
  84218. var BABYLON;
  84219. (function (BABYLON) {
  84220. // Adds the parser to the scene parsers.
  84221. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84222. // Lens flares
  84223. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84224. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84225. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84226. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84227. container.lensFlareSystems.push(lf);
  84228. }
  84229. }
  84230. });
  84231. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84232. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84233. if (this.lensFlareSystems[index].name === name) {
  84234. return this.lensFlareSystems[index];
  84235. }
  84236. }
  84237. return null;
  84238. };
  84239. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84240. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84241. if (this.lensFlareSystems[index].id === id) {
  84242. return this.lensFlareSystems[index];
  84243. }
  84244. }
  84245. return null;
  84246. };
  84247. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84248. var index = this.lensFlareSystems.indexOf(toRemove);
  84249. if (index !== -1) {
  84250. this.lensFlareSystems.splice(index, 1);
  84251. }
  84252. return index;
  84253. };
  84254. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84255. this.lensFlareSystems.push(newLensFlareSystem);
  84256. };
  84257. /**
  84258. * Defines the layer scene component responsible to manage any layers
  84259. * in a given scene.
  84260. */
  84261. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84262. /**
  84263. * Creates a new instance of the component for the given scene
  84264. * @param scene Defines the scene to register the component in
  84265. */
  84266. function LensFlareSystemSceneComponent(scene) {
  84267. /**
  84268. * The component name helpfull to identify the component in the list of scene components.
  84269. */
  84270. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84271. this.scene = scene;
  84272. this._lensFlareSystems = scene.lensFlareSystems = new Array();
  84273. }
  84274. /**
  84275. * Registers the component in a given scene
  84276. */
  84277. LensFlareSystemSceneComponent.prototype.register = function () {
  84278. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84279. };
  84280. /**
  84281. * Rebuilds the elements related to this component in case of
  84282. * context lost for instance.
  84283. */
  84284. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84285. // Nothing to do for lens flare
  84286. };
  84287. /**
  84288. * Adds all the element from the container to the scene
  84289. * @param container the container holding the elements
  84290. */
  84291. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84292. var _this = this;
  84293. if (!container.lensFlareSystems) {
  84294. return;
  84295. }
  84296. container.lensFlareSystems.forEach(function (o) {
  84297. _this.scene.addLensFlareSystem(o);
  84298. });
  84299. };
  84300. /**
  84301. * Removes all the elements in the container from the scene
  84302. * @param container contains the elements to remove
  84303. */
  84304. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84305. var _this = this;
  84306. if (!container.lensFlareSystems) {
  84307. return;
  84308. }
  84309. container.lensFlareSystems.forEach(function (o) {
  84310. _this.scene.removeLensFlareSystem(o);
  84311. });
  84312. };
  84313. /**
  84314. * Serializes the component data to the specified json object
  84315. * @param serializationObject The object to serialize to
  84316. */
  84317. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84318. // Lens flares
  84319. serializationObject.lensFlareSystems = [];
  84320. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84321. var lensFlareSystem = _a[_i];
  84322. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84323. }
  84324. };
  84325. /**
  84326. * Disposes the component and the associated ressources.
  84327. */
  84328. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84329. while (this._lensFlareSystems.length) {
  84330. this._lensFlareSystems[0].dispose();
  84331. }
  84332. };
  84333. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84334. // Lens flares
  84335. if (this.scene.lensFlaresEnabled) {
  84336. BABYLON.Tools.StartPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84337. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84338. var lensFlareSystem = _a[_i];
  84339. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84340. lensFlareSystem.render();
  84341. }
  84342. }
  84343. BABYLON.Tools.EndPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84344. }
  84345. };
  84346. return LensFlareSystemSceneComponent;
  84347. }());
  84348. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84349. })(BABYLON || (BABYLON = {}));
  84350. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84351. var BABYLON;
  84352. (function (BABYLON) {
  84353. var LensFlareSystem = /** @class */ (function () {
  84354. function LensFlareSystem(name, emitter, scene) {
  84355. this.name = name;
  84356. this.lensFlares = new Array();
  84357. this.borderLimit = 300;
  84358. this.viewportBorder = 0;
  84359. this.layerMask = 0x0FFFFFFF;
  84360. this._vertexBuffers = {};
  84361. this._isEnabled = true;
  84362. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84363. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84364. if (!component) {
  84365. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84366. scene._addComponent(component);
  84367. }
  84368. this._emitter = emitter;
  84369. this.id = name;
  84370. scene.lensFlareSystems.push(this);
  84371. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84372. var engine = scene.getEngine();
  84373. // VBO
  84374. var vertices = [];
  84375. vertices.push(1, 1);
  84376. vertices.push(-1, 1);
  84377. vertices.push(-1, -1);
  84378. vertices.push(1, -1);
  84379. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84380. // Indices
  84381. var indices = [];
  84382. indices.push(0);
  84383. indices.push(1);
  84384. indices.push(2);
  84385. indices.push(0);
  84386. indices.push(2);
  84387. indices.push(3);
  84388. this._indexBuffer = engine.createIndexBuffer(indices);
  84389. // Effects
  84390. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84391. }
  84392. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84393. get: function () {
  84394. return this._isEnabled;
  84395. },
  84396. set: function (value) {
  84397. this._isEnabled = value;
  84398. },
  84399. enumerable: true,
  84400. configurable: true
  84401. });
  84402. LensFlareSystem.prototype.getScene = function () {
  84403. return this._scene;
  84404. };
  84405. LensFlareSystem.prototype.getEmitter = function () {
  84406. return this._emitter;
  84407. };
  84408. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84409. this._emitter = newEmitter;
  84410. };
  84411. LensFlareSystem.prototype.getEmitterPosition = function () {
  84412. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84413. };
  84414. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84415. var position = this.getEmitterPosition();
  84416. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84417. this._positionX = position.x;
  84418. this._positionY = position.y;
  84419. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84420. if (this.viewportBorder > 0) {
  84421. globalViewport.x -= this.viewportBorder;
  84422. globalViewport.y -= this.viewportBorder;
  84423. globalViewport.width += this.viewportBorder * 2;
  84424. globalViewport.height += this.viewportBorder * 2;
  84425. position.x += this.viewportBorder;
  84426. position.y += this.viewportBorder;
  84427. this._positionX += this.viewportBorder;
  84428. this._positionY += this.viewportBorder;
  84429. }
  84430. if (position.z > 0) {
  84431. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84432. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84433. return true;
  84434. }
  84435. return true;
  84436. }
  84437. return false;
  84438. };
  84439. LensFlareSystem.prototype._isVisible = function () {
  84440. if (!this._isEnabled || !this._scene.activeCamera) {
  84441. return false;
  84442. }
  84443. var emitterPosition = this.getEmitterPosition();
  84444. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84445. var distance = direction.length();
  84446. direction.normalize();
  84447. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84448. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84449. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84450. };
  84451. LensFlareSystem.prototype.render = function () {
  84452. if (!this._effect.isReady() || !this._scene.activeCamera)
  84453. return false;
  84454. var engine = this._scene.getEngine();
  84455. var viewport = this._scene.activeCamera.viewport;
  84456. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84457. // Position
  84458. if (!this.computeEffectivePosition(globalViewport)) {
  84459. return false;
  84460. }
  84461. // Visibility
  84462. if (!this._isVisible()) {
  84463. return false;
  84464. }
  84465. // Intensity
  84466. var awayX;
  84467. var awayY;
  84468. if (this._positionX < this.borderLimit + globalViewport.x) {
  84469. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84470. }
  84471. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84472. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84473. }
  84474. else {
  84475. awayX = 0;
  84476. }
  84477. if (this._positionY < this.borderLimit + globalViewport.y) {
  84478. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84479. }
  84480. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84481. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84482. }
  84483. else {
  84484. awayY = 0;
  84485. }
  84486. var away = (awayX > awayY) ? awayX : awayY;
  84487. away -= this.viewportBorder;
  84488. if (away > this.borderLimit) {
  84489. away = this.borderLimit;
  84490. }
  84491. var intensity = 1.0 - (away / this.borderLimit);
  84492. if (intensity < 0) {
  84493. return false;
  84494. }
  84495. if (intensity > 1.0) {
  84496. intensity = 1.0;
  84497. }
  84498. if (this.viewportBorder > 0) {
  84499. globalViewport.x += this.viewportBorder;
  84500. globalViewport.y += this.viewportBorder;
  84501. globalViewport.width -= this.viewportBorder * 2;
  84502. globalViewport.height -= this.viewportBorder * 2;
  84503. this._positionX -= this.viewportBorder;
  84504. this._positionY -= this.viewportBorder;
  84505. }
  84506. // Position
  84507. var centerX = globalViewport.x + globalViewport.width / 2;
  84508. var centerY = globalViewport.y + globalViewport.height / 2;
  84509. var distX = centerX - this._positionX;
  84510. var distY = centerY - this._positionY;
  84511. // Effects
  84512. engine.enableEffect(this._effect);
  84513. engine.setState(false);
  84514. engine.setDepthBuffer(false);
  84515. // VBOs
  84516. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84517. // Flares
  84518. for (var index = 0; index < this.lensFlares.length; index++) {
  84519. var flare = this.lensFlares[index];
  84520. engine.setAlphaMode(flare.alphaMode);
  84521. var x = centerX - (distX * flare.position);
  84522. var y = centerY - (distY * flare.position);
  84523. var cw = flare.size;
  84524. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84525. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84526. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84527. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84528. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84529. // Texture
  84530. this._effect.setTexture("textureSampler", flare.texture);
  84531. // Color
  84532. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84533. // Draw order
  84534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84535. }
  84536. engine.setDepthBuffer(true);
  84537. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84538. return true;
  84539. };
  84540. LensFlareSystem.prototype.dispose = function () {
  84541. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84542. if (vertexBuffer) {
  84543. vertexBuffer.dispose();
  84544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84545. }
  84546. if (this._indexBuffer) {
  84547. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84548. this._indexBuffer = null;
  84549. }
  84550. while (this.lensFlares.length) {
  84551. this.lensFlares[0].dispose();
  84552. }
  84553. // Remove from scene
  84554. var index = this._scene.lensFlareSystems.indexOf(this);
  84555. this._scene.lensFlareSystems.splice(index, 1);
  84556. };
  84557. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84558. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84559. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84560. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84561. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84562. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84563. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84564. var parsedFlare = parsedLensFlareSystem.flares[index];
  84565. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84566. }
  84567. return lensFlareSystem;
  84568. };
  84569. LensFlareSystem.prototype.serialize = function () {
  84570. var serializationObject = {};
  84571. serializationObject.id = this.id;
  84572. serializationObject.name = this.name;
  84573. serializationObject.emitterId = this.getEmitter().id;
  84574. serializationObject.borderLimit = this.borderLimit;
  84575. serializationObject.flares = [];
  84576. for (var index = 0; index < this.lensFlares.length; index++) {
  84577. var flare = this.lensFlares[index];
  84578. serializationObject.flares.push({
  84579. size: flare.size,
  84580. position: flare.position,
  84581. color: flare.color.asArray(),
  84582. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84583. });
  84584. }
  84585. return serializationObject;
  84586. };
  84587. return LensFlareSystem;
  84588. }());
  84589. BABYLON.LensFlareSystem = LensFlareSystem;
  84590. })(BABYLON || (BABYLON = {}));
  84591. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84592. var BABYLON;
  84593. (function (BABYLON) {
  84594. /**
  84595. * This is a holder class for the physics joint created by the physics plugin.
  84596. * It holds a set of functions to control the underlying joint.
  84597. */
  84598. var PhysicsJoint = /** @class */ (function () {
  84599. function PhysicsJoint(type, jointData) {
  84600. this.type = type;
  84601. this.jointData = jointData;
  84602. jointData.nativeParams = jointData.nativeParams || {};
  84603. }
  84604. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84605. get: function () {
  84606. return this._physicsJoint;
  84607. },
  84608. set: function (newJoint) {
  84609. if (this._physicsJoint) {
  84610. //remove from the wolrd
  84611. }
  84612. this._physicsJoint = newJoint;
  84613. },
  84614. enumerable: true,
  84615. configurable: true
  84616. });
  84617. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84618. set: function (physicsPlugin) {
  84619. this._physicsPlugin = physicsPlugin;
  84620. },
  84621. enumerable: true,
  84622. configurable: true
  84623. });
  84624. /**
  84625. * Execute a function that is physics-plugin specific.
  84626. * @param {Function} func the function that will be executed.
  84627. * It accepts two parameters: the physics world and the physics joint.
  84628. */
  84629. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84630. func(this._physicsPlugin.world, this._physicsJoint);
  84631. };
  84632. //TODO check if the native joints are the same
  84633. //Joint Types
  84634. PhysicsJoint.DistanceJoint = 0;
  84635. PhysicsJoint.HingeJoint = 1;
  84636. PhysicsJoint.BallAndSocketJoint = 2;
  84637. PhysicsJoint.WheelJoint = 3;
  84638. PhysicsJoint.SliderJoint = 4;
  84639. //OIMO
  84640. PhysicsJoint.PrismaticJoint = 5;
  84641. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84642. PhysicsJoint.UniversalJoint = 6;
  84643. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84644. //Cannon
  84645. //Similar to a Ball-Joint. Different in params
  84646. PhysicsJoint.PointToPointJoint = 8;
  84647. //Cannon only at the moment
  84648. PhysicsJoint.SpringJoint = 9;
  84649. PhysicsJoint.LockJoint = 10;
  84650. return PhysicsJoint;
  84651. }());
  84652. BABYLON.PhysicsJoint = PhysicsJoint;
  84653. /**
  84654. * A class representing a physics distance joint.
  84655. */
  84656. var DistanceJoint = /** @class */ (function (_super) {
  84657. __extends(DistanceJoint, _super);
  84658. function DistanceJoint(jointData) {
  84659. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84660. }
  84661. /**
  84662. * Update the predefined distance.
  84663. */
  84664. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84665. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84666. };
  84667. return DistanceJoint;
  84668. }(PhysicsJoint));
  84669. BABYLON.DistanceJoint = DistanceJoint;
  84670. var MotorEnabledJoint = /** @class */ (function (_super) {
  84671. __extends(MotorEnabledJoint, _super);
  84672. function MotorEnabledJoint(type, jointData) {
  84673. return _super.call(this, type, jointData) || this;
  84674. }
  84675. /**
  84676. * Set the motor values.
  84677. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84678. * @param {number} force the force to apply
  84679. * @param {number} maxForce max force for this motor.
  84680. */
  84681. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84682. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84683. };
  84684. /**
  84685. * Set the motor's limits.
  84686. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84687. */
  84688. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84689. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84690. };
  84691. return MotorEnabledJoint;
  84692. }(PhysicsJoint));
  84693. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84694. /**
  84695. * This class represents a single hinge physics joint
  84696. */
  84697. var HingeJoint = /** @class */ (function (_super) {
  84698. __extends(HingeJoint, _super);
  84699. function HingeJoint(jointData) {
  84700. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84701. }
  84702. /**
  84703. * Set the motor values.
  84704. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84705. * @param {number} force the force to apply
  84706. * @param {number} maxForce max force for this motor.
  84707. */
  84708. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84709. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84710. };
  84711. /**
  84712. * Set the motor's limits.
  84713. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84714. */
  84715. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84716. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84717. };
  84718. return HingeJoint;
  84719. }(MotorEnabledJoint));
  84720. BABYLON.HingeJoint = HingeJoint;
  84721. /**
  84722. * This class represents a dual hinge physics joint (same as wheel joint)
  84723. */
  84724. var Hinge2Joint = /** @class */ (function (_super) {
  84725. __extends(Hinge2Joint, _super);
  84726. function Hinge2Joint(jointData) {
  84727. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84728. }
  84729. /**
  84730. * Set the motor values.
  84731. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84732. * @param {number} force the force to apply
  84733. * @param {number} maxForce max force for this motor.
  84734. * @param {motorIndex} the motor's index, 0 or 1.
  84735. */
  84736. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84737. if (motorIndex === void 0) { motorIndex = 0; }
  84738. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84739. };
  84740. /**
  84741. * Set the motor limits.
  84742. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84743. * @param {number} upperLimit the upper limit
  84744. * @param {number} lowerLimit lower limit
  84745. * @param {motorIndex} the motor's index, 0 or 1.
  84746. */
  84747. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84748. if (motorIndex === void 0) { motorIndex = 0; }
  84749. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84750. };
  84751. return Hinge2Joint;
  84752. }(MotorEnabledJoint));
  84753. BABYLON.Hinge2Joint = Hinge2Joint;
  84754. })(BABYLON || (BABYLON = {}));
  84755. //# sourceMappingURL=babylon.physicsJoint.js.map
  84756. var BABYLON;
  84757. (function (BABYLON) {
  84758. var PhysicsImpostor = /** @class */ (function () {
  84759. function PhysicsImpostor(object, type, _options, _scene) {
  84760. if (_options === void 0) { _options = { mass: 0 }; }
  84761. var _this = this;
  84762. this.object = object;
  84763. this.type = type;
  84764. this._options = _options;
  84765. this._scene = _scene;
  84766. this._bodyUpdateRequired = false;
  84767. this._onBeforePhysicsStepCallbacks = new Array();
  84768. this._onAfterPhysicsStepCallbacks = new Array();
  84769. this._onPhysicsCollideCallbacks = [];
  84770. this._deltaPosition = BABYLON.Vector3.Zero();
  84771. this._isDisposed = false;
  84772. //temp variables for parent rotation calculations
  84773. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84774. this._tmpQuat = new BABYLON.Quaternion();
  84775. this._tmpQuat2 = new BABYLON.Quaternion();
  84776. /**
  84777. * this function is executed by the physics engine.
  84778. */
  84779. this.beforeStep = function () {
  84780. if (!_this._physicsEngine) {
  84781. return;
  84782. }
  84783. _this.object.translate(_this._deltaPosition, -1);
  84784. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84785. _this.object.computeWorldMatrix(false);
  84786. if (_this.object.parent && _this.object.rotationQuaternion) {
  84787. _this.getParentsRotation();
  84788. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84789. }
  84790. else {
  84791. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84792. }
  84793. if (!_this._options.disableBidirectionalTransformation) {
  84794. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84795. }
  84796. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84797. func(_this);
  84798. });
  84799. };
  84800. /**
  84801. * this function is executed by the physics engine.
  84802. */
  84803. this.afterStep = function () {
  84804. if (!_this._physicsEngine) {
  84805. return;
  84806. }
  84807. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84808. func(_this);
  84809. });
  84810. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84811. // object has now its world rotation. needs to be converted to local.
  84812. if (_this.object.parent && _this.object.rotationQuaternion) {
  84813. _this.getParentsRotation();
  84814. _this._tmpQuat.conjugateInPlace();
  84815. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84816. }
  84817. // take the position set and make it the absolute position of this object.
  84818. _this.object.setAbsolutePosition(_this.object.position);
  84819. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84820. _this.object.translate(_this._deltaPosition, 1);
  84821. };
  84822. /**
  84823. * Legacy collision detection event support
  84824. */
  84825. this.onCollideEvent = null;
  84826. //event and body object due to cannon's event-based architecture.
  84827. this.onCollide = function (e) {
  84828. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84829. return;
  84830. }
  84831. if (!_this._physicsEngine) {
  84832. return;
  84833. }
  84834. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84835. if (otherImpostor) {
  84836. // Legacy collision detection event support
  84837. if (_this.onCollideEvent) {
  84838. _this.onCollideEvent(_this, otherImpostor);
  84839. }
  84840. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84841. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84842. }).forEach(function (obj) {
  84843. obj.callback(_this, otherImpostor);
  84844. });
  84845. }
  84846. };
  84847. //sanity check!
  84848. if (!this.object) {
  84849. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84850. return;
  84851. }
  84852. //legacy support for old syntax.
  84853. if (!this._scene && object.getScene) {
  84854. this._scene = object.getScene();
  84855. }
  84856. if (!this._scene) {
  84857. return;
  84858. }
  84859. this._physicsEngine = this._scene.getPhysicsEngine();
  84860. if (!this._physicsEngine) {
  84861. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84862. }
  84863. else {
  84864. //set the object's quaternion, if not set
  84865. if (!this.object.rotationQuaternion) {
  84866. if (this.object.rotation) {
  84867. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84868. }
  84869. else {
  84870. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84871. }
  84872. }
  84873. //default options params
  84874. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84875. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84876. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84877. this._joints = [];
  84878. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84879. if (!this.object.parent || this._options.ignoreParent) {
  84880. this._init();
  84881. }
  84882. else if (this.object.parent.physicsImpostor) {
  84883. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84884. }
  84885. }
  84886. }
  84887. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84888. get: function () {
  84889. return this._isDisposed;
  84890. },
  84891. enumerable: true,
  84892. configurable: true
  84893. });
  84894. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84895. get: function () {
  84896. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84897. },
  84898. set: function (value) {
  84899. this.setMass(value);
  84900. },
  84901. enumerable: true,
  84902. configurable: true
  84903. });
  84904. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84905. get: function () {
  84906. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84907. },
  84908. set: function (value) {
  84909. if (!this._physicsEngine) {
  84910. return;
  84911. }
  84912. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84913. },
  84914. enumerable: true,
  84915. configurable: true
  84916. });
  84917. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84918. get: function () {
  84919. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84920. },
  84921. set: function (value) {
  84922. if (!this._physicsEngine) {
  84923. return;
  84924. }
  84925. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84926. },
  84927. enumerable: true,
  84928. configurable: true
  84929. });
  84930. /**
  84931. * This function will completly initialize this impostor.
  84932. * It will create a new body - but only if this mesh has no parent.
  84933. * If it has, this impostor will not be used other than to define the impostor
  84934. * of the child mesh.
  84935. */
  84936. PhysicsImpostor.prototype._init = function () {
  84937. if (!this._physicsEngine) {
  84938. return;
  84939. }
  84940. this._physicsEngine.removeImpostor(this);
  84941. this.physicsBody = null;
  84942. this._parent = this._parent || this._getPhysicsParent();
  84943. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84944. this._physicsEngine.addImpostor(this);
  84945. }
  84946. };
  84947. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84948. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84949. var parentMesh = this.object.parent;
  84950. return parentMesh.physicsImpostor;
  84951. }
  84952. return null;
  84953. };
  84954. /**
  84955. * Should a new body be generated.
  84956. */
  84957. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84958. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84959. };
  84960. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84961. this.forceUpdate();
  84962. };
  84963. /**
  84964. * Force a regeneration of this or the parent's impostor's body.
  84965. * Use under cautious - This will remove all joints already implemented.
  84966. */
  84967. PhysicsImpostor.prototype.forceUpdate = function () {
  84968. this._init();
  84969. if (this.parent && !this._options.ignoreParent) {
  84970. this.parent.forceUpdate();
  84971. }
  84972. };
  84973. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84974. /*public get mesh(): AbstractMesh {
  84975. return this._mesh;
  84976. }*/
  84977. /**
  84978. * Gets the body that holds this impostor. Either its own, or its parent.
  84979. */
  84980. get: function () {
  84981. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84982. },
  84983. /**
  84984. * Set the physics body. Used mainly by the physics engine/plugin
  84985. */
  84986. set: function (physicsBody) {
  84987. if (this._physicsBody && this._physicsEngine) {
  84988. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84989. }
  84990. this._physicsBody = physicsBody;
  84991. this.resetUpdateFlags();
  84992. },
  84993. enumerable: true,
  84994. configurable: true
  84995. });
  84996. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84997. get: function () {
  84998. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84999. },
  85000. set: function (value) {
  85001. this._parent = value;
  85002. },
  85003. enumerable: true,
  85004. configurable: true
  85005. });
  85006. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85007. this._bodyUpdateRequired = false;
  85008. };
  85009. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85010. if (this.object.getBoundingInfo) {
  85011. var q = this.object.rotationQuaternion;
  85012. //reset rotation
  85013. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85014. //calculate the world matrix with no rotation
  85015. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85016. var boundingInfo = this.object.getBoundingInfo();
  85017. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85018. //bring back the rotation
  85019. this.object.rotationQuaternion = q;
  85020. //calculate the world matrix with the new rotation
  85021. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85022. return size;
  85023. }
  85024. else {
  85025. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85026. }
  85027. };
  85028. PhysicsImpostor.prototype.getObjectCenter = function () {
  85029. if (this.object.getBoundingInfo) {
  85030. var boundingInfo = this.object.getBoundingInfo();
  85031. return boundingInfo.boundingBox.centerWorld;
  85032. }
  85033. else {
  85034. return this.object.position;
  85035. }
  85036. };
  85037. /**
  85038. * Get a specific parametes from the options parameter.
  85039. */
  85040. PhysicsImpostor.prototype.getParam = function (paramName) {
  85041. return this._options[paramName];
  85042. };
  85043. /**
  85044. * Sets a specific parameter in the options given to the physics plugin
  85045. */
  85046. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85047. this._options[paramName] = value;
  85048. this._bodyUpdateRequired = true;
  85049. };
  85050. /**
  85051. * Specifically change the body's mass option. Won't recreate the physics body object
  85052. */
  85053. PhysicsImpostor.prototype.setMass = function (mass) {
  85054. if (this.getParam("mass") !== mass) {
  85055. this.setParam("mass", mass);
  85056. }
  85057. if (this._physicsEngine) {
  85058. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85059. }
  85060. };
  85061. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85062. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85063. };
  85064. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85065. if (this._physicsEngine) {
  85066. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85067. }
  85068. };
  85069. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85070. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85071. };
  85072. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85073. if (this._physicsEngine) {
  85074. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85075. }
  85076. };
  85077. /**
  85078. * Execute a function with the physics plugin native code.
  85079. * Provide a function the will have two variables - the world object and the physics body object.
  85080. */
  85081. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85082. if (this._physicsEngine) {
  85083. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85084. }
  85085. };
  85086. /**
  85087. * Register a function that will be executed before the physics world is stepping forward.
  85088. */
  85089. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85090. this._onBeforePhysicsStepCallbacks.push(func);
  85091. };
  85092. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85093. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85094. if (index > -1) {
  85095. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85096. }
  85097. else {
  85098. BABYLON.Tools.Warn("Function to remove was not found");
  85099. }
  85100. };
  85101. /**
  85102. * Register a function that will be executed after the physics step
  85103. */
  85104. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85105. this._onAfterPhysicsStepCallbacks.push(func);
  85106. };
  85107. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85108. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85109. if (index > -1) {
  85110. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85111. }
  85112. else {
  85113. BABYLON.Tools.Warn("Function to remove was not found");
  85114. }
  85115. };
  85116. /**
  85117. * register a function that will be executed when this impostor collides against a different body.
  85118. */
  85119. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85120. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85121. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85122. };
  85123. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85124. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85125. var index = -1;
  85126. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85127. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85128. // chcek the arrays match
  85129. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85130. return collidedAgainstList.indexOf(impostor) > -1;
  85131. });
  85132. if (sameList) {
  85133. index = idx;
  85134. }
  85135. return sameList;
  85136. }
  85137. return false;
  85138. });
  85139. if (found) {
  85140. this._onPhysicsCollideCallbacks.splice(index, 1);
  85141. }
  85142. else {
  85143. BABYLON.Tools.Warn("Function to remove was not found");
  85144. }
  85145. };
  85146. PhysicsImpostor.prototype.getParentsRotation = function () {
  85147. var parent = this.object.parent;
  85148. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85149. while (parent) {
  85150. if (parent.rotationQuaternion) {
  85151. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85152. }
  85153. else {
  85154. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85155. }
  85156. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85157. parent = parent.parent;
  85158. }
  85159. return this._tmpQuat;
  85160. };
  85161. /**
  85162. * Apply a force
  85163. */
  85164. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85165. if (this._physicsEngine) {
  85166. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85167. }
  85168. return this;
  85169. };
  85170. /**
  85171. * Apply an impulse
  85172. */
  85173. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85174. if (this._physicsEngine) {
  85175. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85176. }
  85177. return this;
  85178. };
  85179. /**
  85180. * A help function to create a joint.
  85181. */
  85182. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85183. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85184. this.addJoint(otherImpostor, joint);
  85185. return this;
  85186. };
  85187. /**
  85188. * Add a joint to this impostor with a different impostor.
  85189. */
  85190. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85191. this._joints.push({
  85192. otherImpostor: otherImpostor,
  85193. joint: joint
  85194. });
  85195. if (this._physicsEngine) {
  85196. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85197. }
  85198. return this;
  85199. };
  85200. /**
  85201. * Will keep this body still, in a sleep mode.
  85202. */
  85203. PhysicsImpostor.prototype.sleep = function () {
  85204. if (this._physicsEngine) {
  85205. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85206. }
  85207. return this;
  85208. };
  85209. /**
  85210. * Wake the body up.
  85211. */
  85212. PhysicsImpostor.prototype.wakeUp = function () {
  85213. if (this._physicsEngine) {
  85214. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85215. }
  85216. return this;
  85217. };
  85218. PhysicsImpostor.prototype.clone = function (newObject) {
  85219. if (!newObject)
  85220. return null;
  85221. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85222. };
  85223. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85224. var _this = this;
  85225. //no dispose if no physics engine is available.
  85226. if (!this._physicsEngine) {
  85227. return;
  85228. }
  85229. this._joints.forEach(function (j) {
  85230. if (_this._physicsEngine) {
  85231. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85232. }
  85233. });
  85234. //dispose the physics body
  85235. this._physicsEngine.removeImpostor(this);
  85236. if (this.parent) {
  85237. this.parent.forceUpdate();
  85238. }
  85239. else {
  85240. /*this._object.getChildMeshes().forEach(function(mesh) {
  85241. if (mesh.physicsImpostor) {
  85242. if (disposeChildren) {
  85243. mesh.physicsImpostor.dispose();
  85244. mesh.physicsImpostor = null;
  85245. }
  85246. }
  85247. })*/
  85248. }
  85249. this._isDisposed = true;
  85250. };
  85251. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85252. this._deltaPosition.copyFrom(position);
  85253. };
  85254. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85255. if (!this._deltaRotation) {
  85256. this._deltaRotation = new BABYLON.Quaternion();
  85257. }
  85258. this._deltaRotation.copyFrom(rotation);
  85259. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85260. };
  85261. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85262. if (this._physicsEngine) {
  85263. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85264. }
  85265. return this;
  85266. };
  85267. PhysicsImpostor.prototype.getRadius = function () {
  85268. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85269. };
  85270. /**
  85271. * Sync a bone with this impostor
  85272. * @param bone The bone to sync to the impostor.
  85273. * @param boneMesh The mesh that the bone is influencing.
  85274. * @param jointPivot The pivot of the joint / bone in local space.
  85275. * @param distToJoint Optional distance from the impostor to the joint.
  85276. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85277. */
  85278. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85279. var tempVec = PhysicsImpostor._tmpVecs[0];
  85280. var mesh = this.object;
  85281. if (mesh.rotationQuaternion) {
  85282. if (adjustRotation) {
  85283. var tempQuat = PhysicsImpostor._tmpQuat;
  85284. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85285. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85286. }
  85287. else {
  85288. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85289. }
  85290. }
  85291. tempVec.x = 0;
  85292. tempVec.y = 0;
  85293. tempVec.z = 0;
  85294. if (jointPivot) {
  85295. tempVec.x = jointPivot.x;
  85296. tempVec.y = jointPivot.y;
  85297. tempVec.z = jointPivot.z;
  85298. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85299. if (distToJoint === undefined || distToJoint === null) {
  85300. distToJoint = jointPivot.length();
  85301. }
  85302. tempVec.x *= distToJoint;
  85303. tempVec.y *= distToJoint;
  85304. tempVec.z *= distToJoint;
  85305. }
  85306. if (bone.getParent()) {
  85307. tempVec.addInPlace(mesh.getAbsolutePosition());
  85308. bone.setAbsolutePosition(tempVec, boneMesh);
  85309. }
  85310. else {
  85311. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85312. boneMesh.position.x -= tempVec.x;
  85313. boneMesh.position.y -= tempVec.y;
  85314. boneMesh.position.z -= tempVec.z;
  85315. }
  85316. };
  85317. /**
  85318. * Sync impostor to a bone
  85319. * @param bone The bone that the impostor will be synced to.
  85320. * @param boneMesh The mesh that the bone is influencing.
  85321. * @param jointPivot The pivot of the joint / bone in local space.
  85322. * @param distToJoint Optional distance from the impostor to the joint.
  85323. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85324. * @param boneAxis Optional vector3 axis the bone is aligned with
  85325. */
  85326. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85327. var mesh = this.object;
  85328. if (mesh.rotationQuaternion) {
  85329. if (adjustRotation) {
  85330. var tempQuat = PhysicsImpostor._tmpQuat;
  85331. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85332. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85333. }
  85334. else {
  85335. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85336. }
  85337. }
  85338. var pos = PhysicsImpostor._tmpVecs[0];
  85339. var boneDir = PhysicsImpostor._tmpVecs[1];
  85340. if (!boneAxis) {
  85341. boneAxis = PhysicsImpostor._tmpVecs[2];
  85342. boneAxis.x = 0;
  85343. boneAxis.y = 1;
  85344. boneAxis.z = 0;
  85345. }
  85346. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85347. bone.getAbsolutePositionToRef(boneMesh, pos);
  85348. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85349. distToJoint = jointPivot.length();
  85350. }
  85351. if (distToJoint !== undefined && distToJoint !== null) {
  85352. pos.x += boneDir.x * distToJoint;
  85353. pos.y += boneDir.y * distToJoint;
  85354. pos.z += boneDir.z * distToJoint;
  85355. }
  85356. mesh.setAbsolutePosition(pos);
  85357. };
  85358. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85359. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85360. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85361. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85362. //Impostor types
  85363. PhysicsImpostor.NoImpostor = 0;
  85364. PhysicsImpostor.SphereImpostor = 1;
  85365. PhysicsImpostor.BoxImpostor = 2;
  85366. PhysicsImpostor.PlaneImpostor = 3;
  85367. PhysicsImpostor.MeshImpostor = 4;
  85368. PhysicsImpostor.CylinderImpostor = 7;
  85369. PhysicsImpostor.ParticleImpostor = 8;
  85370. PhysicsImpostor.HeightmapImpostor = 9;
  85371. return PhysicsImpostor;
  85372. }());
  85373. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85374. })(BABYLON || (BABYLON = {}));
  85375. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85376. var BABYLON;
  85377. (function (BABYLON) {
  85378. var PhysicsEngine = /** @class */ (function () {
  85379. function PhysicsEngine(gravity, _physicsPlugin) {
  85380. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85381. this._physicsPlugin = _physicsPlugin;
  85382. //new methods and parameters
  85383. this._impostors = [];
  85384. this._joints = [];
  85385. if (!this._physicsPlugin.isSupported()) {
  85386. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85387. + "Please make sure it is included.");
  85388. }
  85389. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85390. this.setGravity(gravity);
  85391. this.setTimeStep();
  85392. }
  85393. PhysicsEngine.prototype.setGravity = function (gravity) {
  85394. this.gravity = gravity;
  85395. this._physicsPlugin.setGravity(this.gravity);
  85396. };
  85397. /**
  85398. * Set the time step of the physics engine.
  85399. * default is 1/60.
  85400. * To slow it down, enter 1/600 for example.
  85401. * To speed it up, 1/30
  85402. * @param {number} newTimeStep the new timestep to apply to this world.
  85403. */
  85404. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85405. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85406. this._physicsPlugin.setTimeStep(newTimeStep);
  85407. };
  85408. /**
  85409. * Get the time step of the physics engine.
  85410. */
  85411. PhysicsEngine.prototype.getTimeStep = function () {
  85412. return this._physicsPlugin.getTimeStep();
  85413. };
  85414. PhysicsEngine.prototype.dispose = function () {
  85415. this._impostors.forEach(function (impostor) {
  85416. impostor.dispose();
  85417. });
  85418. this._physicsPlugin.dispose();
  85419. };
  85420. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85421. return this._physicsPlugin.name;
  85422. };
  85423. /**
  85424. * Adding a new impostor for the impostor tracking.
  85425. * This will be done by the impostor itself.
  85426. * @param {PhysicsImpostor} impostor the impostor to add
  85427. */
  85428. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85429. impostor.uniqueId = this._impostors.push(impostor);
  85430. //if no parent, generate the body
  85431. if (!impostor.parent) {
  85432. this._physicsPlugin.generatePhysicsBody(impostor);
  85433. }
  85434. };
  85435. /**
  85436. * Remove an impostor from the engine.
  85437. * This impostor and its mesh will not longer be updated by the physics engine.
  85438. * @param {PhysicsImpostor} impostor the impostor to remove
  85439. */
  85440. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85441. var index = this._impostors.indexOf(impostor);
  85442. if (index > -1) {
  85443. var removed = this._impostors.splice(index, 1);
  85444. //Is it needed?
  85445. if (removed.length) {
  85446. //this will also remove it from the world.
  85447. removed[0].physicsBody = null;
  85448. }
  85449. }
  85450. };
  85451. /**
  85452. * Add a joint to the physics engine
  85453. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85454. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85455. * @param {PhysicsJoint} the joint that will connect both impostors.
  85456. */
  85457. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85458. var impostorJoint = {
  85459. mainImpostor: mainImpostor,
  85460. connectedImpostor: connectedImpostor,
  85461. joint: joint
  85462. };
  85463. joint.physicsPlugin = this._physicsPlugin;
  85464. this._joints.push(impostorJoint);
  85465. this._physicsPlugin.generateJoint(impostorJoint);
  85466. };
  85467. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85468. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85469. return (impostorJoint.connectedImpostor === connectedImpostor
  85470. && impostorJoint.joint === joint
  85471. && impostorJoint.mainImpostor === mainImpostor);
  85472. });
  85473. if (matchingJoints.length) {
  85474. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85475. //TODO remove it from the list as well
  85476. }
  85477. };
  85478. /**
  85479. * Called by the scene. no need to call it.
  85480. */
  85481. PhysicsEngine.prototype._step = function (delta) {
  85482. var _this = this;
  85483. //check if any mesh has no body / requires an update
  85484. this._impostors.forEach(function (impostor) {
  85485. if (impostor.isBodyInitRequired()) {
  85486. _this._physicsPlugin.generatePhysicsBody(impostor);
  85487. }
  85488. });
  85489. if (delta > 0.1) {
  85490. delta = 0.1;
  85491. }
  85492. else if (delta <= 0) {
  85493. delta = 1.0 / 60.0;
  85494. }
  85495. this._physicsPlugin.executeStep(delta, this._impostors);
  85496. };
  85497. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85498. return this._physicsPlugin;
  85499. };
  85500. PhysicsEngine.prototype.getImpostors = function () {
  85501. return this._impostors;
  85502. };
  85503. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85504. for (var i = 0; i < this._impostors.length; ++i) {
  85505. if (this._impostors[i].object === object) {
  85506. return this._impostors[i];
  85507. }
  85508. }
  85509. return null;
  85510. };
  85511. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85512. for (var i = 0; i < this._impostors.length; ++i) {
  85513. if (this._impostors[i].physicsBody === body) {
  85514. return this._impostors[i];
  85515. }
  85516. }
  85517. return null;
  85518. };
  85519. // Statics
  85520. PhysicsEngine.Epsilon = 0.001;
  85521. return PhysicsEngine;
  85522. }());
  85523. BABYLON.PhysicsEngine = PhysicsEngine;
  85524. })(BABYLON || (BABYLON = {}));
  85525. //# sourceMappingURL=babylon.physicsEngine.js.map
  85526. var BABYLON;
  85527. (function (BABYLON) {
  85528. var PhysicsHelper = /** @class */ (function () {
  85529. function PhysicsHelper(scene) {
  85530. this._scene = scene;
  85531. this._physicsEngine = this._scene.getPhysicsEngine();
  85532. if (!this._physicsEngine) {
  85533. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85534. }
  85535. }
  85536. /**
  85537. * @param {Vector3} origin the origin of the explosion
  85538. * @param {number} radius the explosion radius
  85539. * @param {number} strength the explosion strength
  85540. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85541. */
  85542. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85543. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85544. if (!this._physicsEngine) {
  85545. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85546. return null;
  85547. }
  85548. var impostors = this._physicsEngine.getImpostors();
  85549. if (impostors.length === 0) {
  85550. return null;
  85551. }
  85552. var event = new PhysicsRadialExplosionEvent(this._scene);
  85553. impostors.forEach(function (impostor) {
  85554. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85555. if (!impostorForceAndContactPoint) {
  85556. return;
  85557. }
  85558. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85559. });
  85560. event.dispose(false);
  85561. return event;
  85562. };
  85563. /**
  85564. * @param {Vector3} origin the origin of the explosion
  85565. * @param {number} radius the explosion radius
  85566. * @param {number} strength the explosion strength
  85567. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85568. */
  85569. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85570. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85571. if (!this._physicsEngine) {
  85572. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85573. return null;
  85574. }
  85575. var impostors = this._physicsEngine.getImpostors();
  85576. if (impostors.length === 0) {
  85577. return null;
  85578. }
  85579. var event = new PhysicsRadialExplosionEvent(this._scene);
  85580. impostors.forEach(function (impostor) {
  85581. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85582. if (!impostorForceAndContactPoint) {
  85583. return;
  85584. }
  85585. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85586. });
  85587. event.dispose(false);
  85588. return event;
  85589. };
  85590. /**
  85591. * @param {Vector3} origin the origin of the explosion
  85592. * @param {number} radius the explosion radius
  85593. * @param {number} strength the explosion strength
  85594. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85595. */
  85596. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85597. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85598. if (!this._physicsEngine) {
  85599. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85600. return null;
  85601. }
  85602. var impostors = this._physicsEngine.getImpostors();
  85603. if (impostors.length === 0) {
  85604. return null;
  85605. }
  85606. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85607. event.dispose(false);
  85608. return event;
  85609. };
  85610. /**
  85611. * @param {Vector3} origin the origin of the updraft
  85612. * @param {number} radius the radius of the updraft
  85613. * @param {number} strength the strength of the updraft
  85614. * @param {number} height the height of the updraft
  85615. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85616. */
  85617. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85618. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85619. if (!this._physicsEngine) {
  85620. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85621. return null;
  85622. }
  85623. if (this._physicsEngine.getImpostors().length === 0) {
  85624. return null;
  85625. }
  85626. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85627. event.dispose(false);
  85628. return event;
  85629. };
  85630. /**
  85631. * @param {Vector3} origin the of the vortex
  85632. * @param {number} radius the radius of the vortex
  85633. * @param {number} strength the strength of the vortex
  85634. * @param {number} height the height of the vortex
  85635. */
  85636. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85637. if (!this._physicsEngine) {
  85638. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85639. return null;
  85640. }
  85641. if (this._physicsEngine.getImpostors().length === 0) {
  85642. return null;
  85643. }
  85644. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85645. event.dispose(false);
  85646. return event;
  85647. };
  85648. return PhysicsHelper;
  85649. }());
  85650. BABYLON.PhysicsHelper = PhysicsHelper;
  85651. /***** Radial explosion *****/
  85652. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85653. function PhysicsRadialExplosionEvent(scene) {
  85654. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85655. this._rays = [];
  85656. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85657. this._scene = scene;
  85658. }
  85659. /**
  85660. * Returns the data related to the radial explosion event (sphere & rays).
  85661. * @returns {PhysicsRadialExplosionEventData}
  85662. */
  85663. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85664. this._dataFetched = true;
  85665. return {
  85666. sphere: this._sphere,
  85667. rays: this._rays,
  85668. };
  85669. };
  85670. /**
  85671. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85672. * @param impostor
  85673. * @param {Vector3} origin the origin of the explosion
  85674. * @param {number} radius the explosion radius
  85675. * @param {number} strength the explosion strength
  85676. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85677. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85678. */
  85679. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85680. if (impostor.mass === 0) {
  85681. return null;
  85682. }
  85683. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85684. return null;
  85685. }
  85686. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85687. return null;
  85688. }
  85689. var impostorObjectCenter = impostor.getObjectCenter();
  85690. var direction = impostorObjectCenter.subtract(origin);
  85691. var ray = new BABYLON.Ray(origin, direction, radius);
  85692. this._rays.push(ray);
  85693. var hit = ray.intersectsMesh(impostor.object);
  85694. var contactPoint = hit.pickedPoint;
  85695. if (!contactPoint) {
  85696. return null;
  85697. }
  85698. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85699. if (distanceFromOrigin > radius) {
  85700. return null;
  85701. }
  85702. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85703. ? strength
  85704. : strength * (1 - (distanceFromOrigin / radius));
  85705. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85706. return { force: force, contactPoint: contactPoint };
  85707. };
  85708. /**
  85709. * Disposes the sphere.
  85710. * @param {bolean} force
  85711. */
  85712. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85713. var _this = this;
  85714. if (force === void 0) { force = true; }
  85715. if (force) {
  85716. this._sphere.dispose();
  85717. }
  85718. else {
  85719. setTimeout(function () {
  85720. if (!_this._dataFetched) {
  85721. _this._sphere.dispose();
  85722. }
  85723. }, 0);
  85724. }
  85725. };
  85726. /*** Helpers ***/
  85727. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85728. if (!this._sphere) {
  85729. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85730. this._sphere.isVisible = false;
  85731. }
  85732. };
  85733. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85734. var impostorObject = impostor.object;
  85735. this._prepareSphere();
  85736. this._sphere.position = origin;
  85737. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85738. this._sphere._updateBoundingInfo();
  85739. this._sphere.computeWorldMatrix(true);
  85740. return this._sphere.intersectsMesh(impostorObject, true);
  85741. };
  85742. return PhysicsRadialExplosionEvent;
  85743. }());
  85744. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85745. /***** Gravitational Field *****/
  85746. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85747. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85748. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85749. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85750. this._physicsHelper = physicsHelper;
  85751. this._scene = scene;
  85752. this._origin = origin;
  85753. this._radius = radius;
  85754. this._strength = strength;
  85755. this._falloff = falloff;
  85756. this._tickCallback = this._tick.bind(this);
  85757. }
  85758. /**
  85759. * Returns the data related to the gravitational field event (sphere).
  85760. * @returns {PhysicsGravitationalFieldEventData}
  85761. */
  85762. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85763. this._dataFetched = true;
  85764. return {
  85765. sphere: this._sphere,
  85766. };
  85767. };
  85768. /**
  85769. * Enables the gravitational field.
  85770. */
  85771. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85772. this._tickCallback.call(this);
  85773. this._scene.registerBeforeRender(this._tickCallback);
  85774. };
  85775. /**
  85776. * Disables the gravitational field.
  85777. */
  85778. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85779. this._scene.unregisterBeforeRender(this._tickCallback);
  85780. };
  85781. /**
  85782. * Disposes the sphere.
  85783. * @param {bolean} force
  85784. */
  85785. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85786. var _this = this;
  85787. if (force === void 0) { force = true; }
  85788. if (force) {
  85789. this._sphere.dispose();
  85790. }
  85791. else {
  85792. setTimeout(function () {
  85793. if (!_this._dataFetched) {
  85794. _this._sphere.dispose();
  85795. }
  85796. }, 0);
  85797. }
  85798. };
  85799. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85800. // Since the params won't change, we fetch the event only once
  85801. if (this._sphere) {
  85802. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85803. }
  85804. else {
  85805. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85806. if (radialExplosionEvent) {
  85807. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85808. }
  85809. }
  85810. };
  85811. return PhysicsGravitationalFieldEvent;
  85812. }());
  85813. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85814. /***** Updraft *****/
  85815. var PhysicsUpdraftEvent = /** @class */ (function () {
  85816. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85817. this._scene = _scene;
  85818. this._origin = _origin;
  85819. this._radius = _radius;
  85820. this._strength = _strength;
  85821. this._height = _height;
  85822. this._updraftMode = _updraftMode;
  85823. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85824. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85825. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85826. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85827. this._physicsEngine = this._scene.getPhysicsEngine();
  85828. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85829. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85830. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85831. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85832. }
  85833. this._tickCallback = this._tick.bind(this);
  85834. }
  85835. /**
  85836. * Returns the data related to the updraft event (cylinder).
  85837. * @returns {PhysicsUpdraftEventData}
  85838. */
  85839. PhysicsUpdraftEvent.prototype.getData = function () {
  85840. this._dataFetched = true;
  85841. return {
  85842. cylinder: this._cylinder,
  85843. };
  85844. };
  85845. /**
  85846. * Enables the updraft.
  85847. */
  85848. PhysicsUpdraftEvent.prototype.enable = function () {
  85849. this._tickCallback.call(this);
  85850. this._scene.registerBeforeRender(this._tickCallback);
  85851. };
  85852. /**
  85853. * Disables the cortex.
  85854. */
  85855. PhysicsUpdraftEvent.prototype.disable = function () {
  85856. this._scene.unregisterBeforeRender(this._tickCallback);
  85857. };
  85858. /**
  85859. * Disposes the sphere.
  85860. * @param {bolean} force
  85861. */
  85862. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85863. var _this = this;
  85864. if (force === void 0) { force = true; }
  85865. if (force) {
  85866. this._cylinder.dispose();
  85867. }
  85868. else {
  85869. setTimeout(function () {
  85870. if (!_this._dataFetched) {
  85871. _this._cylinder.dispose();
  85872. }
  85873. }, 0);
  85874. }
  85875. };
  85876. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85877. if (impostor.mass === 0) {
  85878. return null;
  85879. }
  85880. if (!this._intersectsWithCylinder(impostor)) {
  85881. return null;
  85882. }
  85883. var impostorObjectCenter = impostor.getObjectCenter();
  85884. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85885. var direction = this._originDirection;
  85886. }
  85887. else {
  85888. var direction = impostorObjectCenter.subtract(this._originTop);
  85889. }
  85890. var multiplier = this._strength * -1;
  85891. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85892. return { force: force, contactPoint: impostorObjectCenter };
  85893. };
  85894. PhysicsUpdraftEvent.prototype._tick = function () {
  85895. var _this = this;
  85896. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85897. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85898. if (!impostorForceAndContactPoint) {
  85899. return;
  85900. }
  85901. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85902. });
  85903. };
  85904. /*** Helpers ***/
  85905. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85906. if (!this._cylinder) {
  85907. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85908. height: this._height,
  85909. diameter: this._radius * 2,
  85910. }, this._scene);
  85911. this._cylinder.isVisible = false;
  85912. }
  85913. };
  85914. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85915. var impostorObject = impostor.object;
  85916. this._prepareCylinder();
  85917. this._cylinder.position = this._cylinderPosition;
  85918. return this._cylinder.intersectsMesh(impostorObject, true);
  85919. };
  85920. return PhysicsUpdraftEvent;
  85921. }());
  85922. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85923. /***** Vortex *****/
  85924. var PhysicsVortexEvent = /** @class */ (function () {
  85925. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85926. this._scene = _scene;
  85927. this._origin = _origin;
  85928. this._radius = _radius;
  85929. this._strength = _strength;
  85930. this._height = _height;
  85931. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85932. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85933. this._updraftMultiplier = 0.02;
  85934. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85935. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85936. this._physicsEngine = this._scene.getPhysicsEngine();
  85937. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85938. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85939. this._tickCallback = this._tick.bind(this);
  85940. }
  85941. /**
  85942. * Returns the data related to the vortex event (cylinder).
  85943. * @returns {PhysicsVortexEventData}
  85944. */
  85945. PhysicsVortexEvent.prototype.getData = function () {
  85946. this._dataFetched = true;
  85947. return {
  85948. cylinder: this._cylinder,
  85949. };
  85950. };
  85951. /**
  85952. * Enables the vortex.
  85953. */
  85954. PhysicsVortexEvent.prototype.enable = function () {
  85955. this._tickCallback.call(this);
  85956. this._scene.registerBeforeRender(this._tickCallback);
  85957. };
  85958. /**
  85959. * Disables the cortex.
  85960. */
  85961. PhysicsVortexEvent.prototype.disable = function () {
  85962. this._scene.unregisterBeforeRender(this._tickCallback);
  85963. };
  85964. /**
  85965. * Disposes the sphere.
  85966. * @param {bolean} force
  85967. */
  85968. PhysicsVortexEvent.prototype.dispose = function (force) {
  85969. var _this = this;
  85970. if (force === void 0) { force = true; }
  85971. if (force) {
  85972. this._cylinder.dispose();
  85973. }
  85974. else {
  85975. setTimeout(function () {
  85976. if (!_this._dataFetched) {
  85977. _this._cylinder.dispose();
  85978. }
  85979. }, 0);
  85980. }
  85981. };
  85982. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85983. if (impostor.mass === 0) {
  85984. return null;
  85985. }
  85986. if (!this._intersectsWithCylinder(impostor)) {
  85987. return null;
  85988. }
  85989. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85990. return null;
  85991. }
  85992. var impostorObjectCenter = impostor.getObjectCenter();
  85993. 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)
  85994. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85995. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85996. var hit = ray.intersectsMesh(impostor.object);
  85997. var contactPoint = hit.pickedPoint;
  85998. if (!contactPoint) {
  85999. return null;
  86000. }
  86001. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86002. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86003. var directionToOrigin = contactPoint.normalize();
  86004. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86005. directionToOrigin = directionToOrigin.negate();
  86006. }
  86007. // TODO: find a more physically based solution
  86008. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86009. var forceX = directionToOrigin.x * this._strength / 8;
  86010. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86011. var forceZ = directionToOrigin.z * this._strength / 8;
  86012. }
  86013. else {
  86014. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86015. var forceY = this._originTop.y * this._updraftMultiplier;
  86016. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86017. }
  86018. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86019. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86020. return { force: force, contactPoint: impostorObjectCenter };
  86021. };
  86022. PhysicsVortexEvent.prototype._tick = function () {
  86023. var _this = this;
  86024. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86025. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86026. if (!impostorForceAndContactPoint) {
  86027. return;
  86028. }
  86029. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86030. });
  86031. };
  86032. /*** Helpers ***/
  86033. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86034. if (!this._cylinder) {
  86035. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86036. height: this._height,
  86037. diameter: this._radius * 2,
  86038. }, this._scene);
  86039. this._cylinder.isVisible = false;
  86040. }
  86041. };
  86042. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86043. var impostorObject = impostor.object;
  86044. this._prepareCylinder();
  86045. this._cylinder.position = this._cylinderPosition;
  86046. return this._cylinder.intersectsMesh(impostorObject, true);
  86047. };
  86048. return PhysicsVortexEvent;
  86049. }());
  86050. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86051. /***** Enums *****/
  86052. /**
  86053. * The strenght of the force in correspondence to the distance of the affected object
  86054. */
  86055. var PhysicsRadialImpulseFalloff;
  86056. (function (PhysicsRadialImpulseFalloff) {
  86057. /** Defines that impulse is constant in strength across it's whole radius */
  86058. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86059. /** DEfines that impulse gets weaker if it's further from the origin */
  86060. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86061. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86062. /**
  86063. * The strenght of the force in correspondence to the distance of the affected object
  86064. */
  86065. var PhysicsUpdraftMode;
  86066. (function (PhysicsUpdraftMode) {
  86067. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86068. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86069. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86070. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86071. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86072. })(BABYLON || (BABYLON = {}));
  86073. //# sourceMappingURL=babylon.physicsHelper.js.map
  86074. var BABYLON;
  86075. (function (BABYLON) {
  86076. var CannonJSPlugin = /** @class */ (function () {
  86077. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86078. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86079. if (iterations === void 0) { iterations = 10; }
  86080. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86081. this.name = "CannonJSPlugin";
  86082. this._physicsMaterials = new Array();
  86083. this._fixedTimeStep = 1 / 60;
  86084. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86085. this.BJSCANNON = CANNON;
  86086. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86087. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86088. this._tmpPosition = BABYLON.Vector3.Zero();
  86089. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86090. this._tmpUnityRotation = new BABYLON.Quaternion();
  86091. if (!this.isSupported()) {
  86092. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86093. return;
  86094. }
  86095. this._extendNamespace();
  86096. this.world = new this.BJSCANNON.World();
  86097. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86098. this.world.solver.iterations = iterations;
  86099. }
  86100. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86101. this.world.gravity.copy(gravity);
  86102. };
  86103. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86104. this._fixedTimeStep = timeStep;
  86105. };
  86106. CannonJSPlugin.prototype.getTimeStep = function () {
  86107. return this._fixedTimeStep;
  86108. };
  86109. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86110. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86111. };
  86112. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86113. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86114. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86115. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86116. };
  86117. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86118. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86119. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86120. impostor.physicsBody.applyForce(impulse, worldPoint);
  86121. };
  86122. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86123. //parent-child relationship. Does this impostor has a parent impostor?
  86124. if (impostor.parent) {
  86125. if (impostor.physicsBody) {
  86126. this.removePhysicsBody(impostor);
  86127. //TODO is that needed?
  86128. impostor.forceUpdate();
  86129. }
  86130. return;
  86131. }
  86132. //should a new body be created for this impostor?
  86133. if (impostor.isBodyInitRequired()) {
  86134. var shape = this._createShape(impostor);
  86135. //unregister events, if body is being changed
  86136. var oldBody = impostor.physicsBody;
  86137. if (oldBody) {
  86138. this.removePhysicsBody(impostor);
  86139. }
  86140. //create the body and material
  86141. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86142. var bodyCreationObject = {
  86143. mass: impostor.getParam("mass"),
  86144. material: material
  86145. };
  86146. // A simple extend, in case native options were used.
  86147. var nativeOptions = impostor.getParam("nativeOptions");
  86148. for (var key in nativeOptions) {
  86149. if (nativeOptions.hasOwnProperty(key)) {
  86150. bodyCreationObject[key] = nativeOptions[key];
  86151. }
  86152. }
  86153. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86154. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86155. this.world.addEventListener("preStep", impostor.beforeStep);
  86156. this.world.addEventListener("postStep", impostor.afterStep);
  86157. impostor.physicsBody.addShape(shape);
  86158. this.world.add(impostor.physicsBody);
  86159. //try to keep the body moving in the right direction by taking old properties.
  86160. //Should be tested!
  86161. if (oldBody) {
  86162. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86163. impostor.physicsBody[param].copy(oldBody[param]);
  86164. });
  86165. }
  86166. this._processChildMeshes(impostor);
  86167. }
  86168. //now update the body's transformation
  86169. this._updatePhysicsBodyTransformation(impostor);
  86170. };
  86171. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86172. var _this = this;
  86173. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86174. var currentRotation = mainImpostor.object.rotationQuaternion;
  86175. if (meshChildren.length) {
  86176. var processMesh = function (localPosition, mesh) {
  86177. if (!currentRotation || !mesh.rotationQuaternion) {
  86178. return;
  86179. }
  86180. var childImpostor = mesh.getPhysicsImpostor();
  86181. if (childImpostor) {
  86182. var parent = childImpostor.parent;
  86183. if (parent !== mainImpostor) {
  86184. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86185. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86186. if (childImpostor.physicsBody) {
  86187. _this.removePhysicsBody(childImpostor);
  86188. childImpostor.physicsBody = null;
  86189. }
  86190. childImpostor.parent = mainImpostor;
  86191. childImpostor.resetUpdateFlags();
  86192. 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));
  86193. //Add the mass of the children.
  86194. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86195. }
  86196. }
  86197. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86198. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86199. };
  86200. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86201. }
  86202. };
  86203. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86204. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86205. this.world.removeEventListener("preStep", impostor.beforeStep);
  86206. this.world.removeEventListener("postStep", impostor.afterStep);
  86207. this.world.remove(impostor.physicsBody);
  86208. };
  86209. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86210. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86211. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86212. if (!mainBody || !connectedBody) {
  86213. return;
  86214. }
  86215. var constraint;
  86216. var jointData = impostorJoint.joint.jointData;
  86217. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86218. var constraintData = {
  86219. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86220. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86221. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86222. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86223. maxForce: jointData.nativeParams.maxForce,
  86224. collideConnected: !!jointData.collision
  86225. };
  86226. switch (impostorJoint.joint.type) {
  86227. case BABYLON.PhysicsJoint.HingeJoint:
  86228. case BABYLON.PhysicsJoint.Hinge2Joint:
  86229. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86230. break;
  86231. case BABYLON.PhysicsJoint.DistanceJoint:
  86232. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86233. break;
  86234. case BABYLON.PhysicsJoint.SpringJoint:
  86235. var springData = jointData;
  86236. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86237. restLength: springData.length,
  86238. stiffness: springData.stiffness,
  86239. damping: springData.damping,
  86240. localAnchorA: constraintData.pivotA,
  86241. localAnchorB: constraintData.pivotB
  86242. });
  86243. break;
  86244. case BABYLON.PhysicsJoint.LockJoint:
  86245. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86246. break;
  86247. case BABYLON.PhysicsJoint.PointToPointJoint:
  86248. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86249. default:
  86250. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86251. break;
  86252. }
  86253. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86254. constraint.collideConnected = !!jointData.collision;
  86255. impostorJoint.joint.physicsJoint = constraint;
  86256. //don't add spring as constraint, as it is not one.
  86257. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86258. this.world.addConstraint(constraint);
  86259. }
  86260. else {
  86261. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86262. constraint.applyForce();
  86263. });
  86264. }
  86265. };
  86266. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86267. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86268. };
  86269. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86270. var index;
  86271. var mat;
  86272. for (index = 0; index < this._physicsMaterials.length; index++) {
  86273. mat = this._physicsMaterials[index];
  86274. if (mat.friction === friction && mat.restitution === restitution) {
  86275. return mat;
  86276. }
  86277. }
  86278. var currentMat = new this.BJSCANNON.Material(name);
  86279. currentMat.friction = friction;
  86280. currentMat.restitution = restitution;
  86281. this._physicsMaterials.push(currentMat);
  86282. return currentMat;
  86283. };
  86284. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86285. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86286. };
  86287. CannonJSPlugin.prototype._createShape = function (impostor) {
  86288. var object = impostor.object;
  86289. var returnValue;
  86290. var extendSize = impostor.getObjectExtendSize();
  86291. switch (impostor.type) {
  86292. case BABYLON.PhysicsImpostor.SphereImpostor:
  86293. var radiusX = extendSize.x;
  86294. var radiusY = extendSize.y;
  86295. var radiusZ = extendSize.z;
  86296. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86297. break;
  86298. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86299. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86300. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86301. break;
  86302. case BABYLON.PhysicsImpostor.BoxImpostor:
  86303. var box = extendSize.scale(0.5);
  86304. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86305. break;
  86306. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86307. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86308. returnValue = new this.BJSCANNON.Plane();
  86309. break;
  86310. case BABYLON.PhysicsImpostor.MeshImpostor:
  86311. // should transform the vertex data to world coordinates!!
  86312. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86313. var rawFaces = object.getIndices ? object.getIndices() : [];
  86314. if (!rawVerts)
  86315. return;
  86316. // get only scale! so the object could transform correctly.
  86317. var oldPosition = object.position.clone();
  86318. var oldRotation = object.rotation && object.rotation.clone();
  86319. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86320. object.position.copyFromFloats(0, 0, 0);
  86321. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86322. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86323. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86324. var transform = object.computeWorldMatrix(true);
  86325. // convert rawVerts to object space
  86326. var temp = new Array();
  86327. var index;
  86328. for (index = 0; index < rawVerts.length; index += 3) {
  86329. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86330. }
  86331. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86332. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86333. //now set back the transformation!
  86334. object.position.copyFrom(oldPosition);
  86335. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86336. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86337. break;
  86338. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86339. var oldPosition2 = object.position.clone();
  86340. var oldRotation2 = object.rotation && object.rotation.clone();
  86341. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86342. object.position.copyFromFloats(0, 0, 0);
  86343. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86344. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86345. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86346. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86347. returnValue = this._createHeightmap(object);
  86348. object.position.copyFrom(oldPosition2);
  86349. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86350. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86351. object.computeWorldMatrix(true);
  86352. break;
  86353. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86354. returnValue = new this.BJSCANNON.Particle();
  86355. break;
  86356. }
  86357. return returnValue;
  86358. };
  86359. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86360. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86361. var transform = object.computeWorldMatrix(true);
  86362. // convert rawVerts to object space
  86363. var temp = new Array();
  86364. var index;
  86365. for (index = 0; index < pos.length; index += 3) {
  86366. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86367. }
  86368. pos = temp;
  86369. var matrix = new Array();
  86370. //For now pointDepth will not be used and will be automatically calculated.
  86371. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86372. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86373. var boundingInfo = object.getBoundingInfo();
  86374. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86375. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86376. var elementSize = dim * 2 / arraySize;
  86377. for (var i = 0; i < pos.length; i = i + 3) {
  86378. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86379. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86380. var y = -pos[i + 2] + minY;
  86381. if (!matrix[x]) {
  86382. matrix[x] = [];
  86383. }
  86384. if (!matrix[x][z]) {
  86385. matrix[x][z] = y;
  86386. }
  86387. matrix[x][z] = Math.max(y, matrix[x][z]);
  86388. }
  86389. for (var x = 0; x <= arraySize; ++x) {
  86390. if (!matrix[x]) {
  86391. var loc = 1;
  86392. while (!matrix[(x + loc) % arraySize]) {
  86393. loc++;
  86394. }
  86395. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86396. //console.log("missing x", x);
  86397. }
  86398. for (var z = 0; z <= arraySize; ++z) {
  86399. if (!matrix[x][z]) {
  86400. var loc = 1;
  86401. var newValue;
  86402. while (newValue === undefined) {
  86403. newValue = matrix[x][(z + loc++) % arraySize];
  86404. }
  86405. matrix[x][z] = newValue;
  86406. }
  86407. }
  86408. }
  86409. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86410. elementSize: elementSize
  86411. });
  86412. //For future reference, needed for body transformation
  86413. shape.minY = minY;
  86414. return shape;
  86415. };
  86416. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86417. var object = impostor.object;
  86418. //make sure it is updated...
  86419. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86420. // The delta between the mesh position and the mesh bounding box center
  86421. var bInfo = object.getBoundingInfo();
  86422. if (!bInfo)
  86423. return;
  86424. var center = impostor.getObjectCenter();
  86425. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86426. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86427. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86428. this._tmpPosition.copyFrom(center);
  86429. var quaternion = object.rotationQuaternion;
  86430. if (!quaternion) {
  86431. return;
  86432. }
  86433. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86434. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86435. //-90 DEG in X, precalculated
  86436. quaternion = quaternion.multiply(this._minus90X);
  86437. //Invert! (Precalculated, 90 deg in X)
  86438. //No need to clone. this will never change.
  86439. impostor.setDeltaRotation(this._plus90X);
  86440. }
  86441. //If it is a heightfield, if should be centered.
  86442. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86443. var mesh = object;
  86444. var boundingInfo = mesh.getBoundingInfo();
  86445. //calculate the correct body position:
  86446. var rotationQuaternion = mesh.rotationQuaternion;
  86447. mesh.rotationQuaternion = this._tmpUnityRotation;
  86448. mesh.computeWorldMatrix(true);
  86449. //get original center with no rotation
  86450. var c = center.clone();
  86451. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86452. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86453. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86454. mesh.setPreTransformMatrix(p);
  86455. mesh.computeWorldMatrix(true);
  86456. //calculate the translation
  86457. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86458. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86459. //add it inverted to the delta
  86460. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86461. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86462. //rotation is back
  86463. mesh.rotationQuaternion = rotationQuaternion;
  86464. mesh.setPreTransformMatrix(oldPivot);
  86465. mesh.computeWorldMatrix(true);
  86466. }
  86467. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86468. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86469. //this._tmpPosition.copyFrom(object.position);
  86470. }
  86471. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86472. //Now update the impostor object
  86473. impostor.physicsBody.position.copy(this._tmpPosition);
  86474. impostor.physicsBody.quaternion.copy(quaternion);
  86475. };
  86476. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86477. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86478. if (impostor.object.rotationQuaternion) {
  86479. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86480. }
  86481. };
  86482. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86483. impostor.physicsBody.position.copy(newPosition);
  86484. impostor.physicsBody.quaternion.copy(newRotation);
  86485. };
  86486. CannonJSPlugin.prototype.isSupported = function () {
  86487. return this.BJSCANNON !== undefined;
  86488. };
  86489. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86490. impostor.physicsBody.velocity.copy(velocity);
  86491. };
  86492. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86493. impostor.physicsBody.angularVelocity.copy(velocity);
  86494. };
  86495. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86496. var v = impostor.physicsBody.velocity;
  86497. if (!v) {
  86498. return null;
  86499. }
  86500. return new BABYLON.Vector3(v.x, v.y, v.z);
  86501. };
  86502. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86503. var v = impostor.physicsBody.angularVelocity;
  86504. if (!v) {
  86505. return null;
  86506. }
  86507. return new BABYLON.Vector3(v.x, v.y, v.z);
  86508. };
  86509. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86510. impostor.physicsBody.mass = mass;
  86511. impostor.physicsBody.updateMassProperties();
  86512. };
  86513. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86514. return impostor.physicsBody.mass;
  86515. };
  86516. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86517. return impostor.physicsBody.material.friction;
  86518. };
  86519. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86520. impostor.physicsBody.material.friction = friction;
  86521. };
  86522. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86523. return impostor.physicsBody.material.restitution;
  86524. };
  86525. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86526. impostor.physicsBody.material.restitution = restitution;
  86527. };
  86528. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86529. impostor.physicsBody.sleep();
  86530. };
  86531. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86532. impostor.physicsBody.wakeUp();
  86533. };
  86534. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86535. joint.physicsJoint.distance = maxDistance;
  86536. };
  86537. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86538. // if (!motorIndex) {
  86539. // joint.physicsJoint.enableMotor();
  86540. // }
  86541. // }
  86542. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86543. // if (!motorIndex) {
  86544. // joint.physicsJoint.disableMotor();
  86545. // }
  86546. // }
  86547. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86548. if (!motorIndex) {
  86549. joint.physicsJoint.enableMotor();
  86550. joint.physicsJoint.setMotorSpeed(speed);
  86551. if (maxForce) {
  86552. this.setLimit(joint, maxForce);
  86553. }
  86554. }
  86555. };
  86556. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86557. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86558. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86559. };
  86560. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86561. var body = impostor.physicsBody;
  86562. mesh.position.x = body.position.x;
  86563. mesh.position.y = body.position.y;
  86564. mesh.position.z = body.position.z;
  86565. if (mesh.rotationQuaternion) {
  86566. mesh.rotationQuaternion.x = body.quaternion.x;
  86567. mesh.rotationQuaternion.y = body.quaternion.y;
  86568. mesh.rotationQuaternion.z = body.quaternion.z;
  86569. mesh.rotationQuaternion.w = body.quaternion.w;
  86570. }
  86571. };
  86572. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86573. var shape = impostor.physicsBody.shapes[0];
  86574. return shape.boundingSphereRadius;
  86575. };
  86576. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86577. var shape = impostor.physicsBody.shapes[0];
  86578. result.x = shape.halfExtents.x * 2;
  86579. result.y = shape.halfExtents.y * 2;
  86580. result.z = shape.halfExtents.z * 2;
  86581. };
  86582. CannonJSPlugin.prototype.dispose = function () {
  86583. };
  86584. CannonJSPlugin.prototype._extendNamespace = function () {
  86585. //this will force cannon to execute at least one step when using interpolation
  86586. var step_tmp1 = new this.BJSCANNON.Vec3();
  86587. var Engine = this.BJSCANNON;
  86588. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86589. maxSubSteps = maxSubSteps || 10;
  86590. timeSinceLastCalled = timeSinceLastCalled || 0;
  86591. if (timeSinceLastCalled === 0) {
  86592. this.internalStep(dt);
  86593. this.time += dt;
  86594. }
  86595. else {
  86596. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86597. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86598. var t0 = performance.now();
  86599. for (var i = 0; i !== internalSteps; i++) {
  86600. this.internalStep(dt);
  86601. if (performance.now() - t0 > dt * 1000) {
  86602. break;
  86603. }
  86604. }
  86605. this.time += timeSinceLastCalled;
  86606. var h = this.time % dt;
  86607. var h_div_dt = h / dt;
  86608. var interpvelo = step_tmp1;
  86609. var bodies = this.bodies;
  86610. for (var j = 0; j !== bodies.length; j++) {
  86611. var b = bodies[j];
  86612. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86613. b.position.vsub(b.previousPosition, interpvelo);
  86614. interpvelo.scale(h_div_dt, interpvelo);
  86615. b.position.vadd(interpvelo, b.interpolatedPosition);
  86616. }
  86617. else {
  86618. b.interpolatedPosition.copy(b.position);
  86619. b.interpolatedQuaternion.copy(b.quaternion);
  86620. }
  86621. }
  86622. }
  86623. };
  86624. };
  86625. return CannonJSPlugin;
  86626. }());
  86627. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86628. })(BABYLON || (BABYLON = {}));
  86629. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86630. var BABYLON;
  86631. (function (BABYLON) {
  86632. var OimoJSPlugin = /** @class */ (function () {
  86633. function OimoJSPlugin(iterations) {
  86634. this.name = "OimoJSPlugin";
  86635. this._tmpImpostorsArray = [];
  86636. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86637. this.BJSOIMO = OIMO;
  86638. this.world = new this.BJSOIMO.World({
  86639. iterations: iterations
  86640. });
  86641. this.world.clear();
  86642. }
  86643. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86644. this.world.gravity.copy(gravity);
  86645. };
  86646. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86647. this.world.timeStep = timeStep;
  86648. };
  86649. OimoJSPlugin.prototype.getTimeStep = function () {
  86650. return this.world.timeStep;
  86651. };
  86652. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86653. var _this = this;
  86654. impostors.forEach(function (impostor) {
  86655. impostor.beforeStep();
  86656. });
  86657. this.world.step();
  86658. impostors.forEach(function (impostor) {
  86659. impostor.afterStep();
  86660. //update the ordered impostors array
  86661. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86662. });
  86663. //check for collisions
  86664. var contact = this.world.contacts;
  86665. while (contact !== null) {
  86666. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86667. contact = contact.next;
  86668. continue;
  86669. }
  86670. //is this body colliding with any other? get the impostor
  86671. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86672. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86673. if (!mainImpostor || !collidingImpostor) {
  86674. contact = contact.next;
  86675. continue;
  86676. }
  86677. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86678. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86679. contact = contact.next;
  86680. }
  86681. };
  86682. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86683. var mass = impostor.physicsBody.mass;
  86684. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86685. };
  86686. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86687. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86688. this.applyImpulse(impostor, force, contactPoint);
  86689. };
  86690. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86691. var _this = this;
  86692. //parent-child relationship. Does this impostor has a parent impostor?
  86693. if (impostor.parent) {
  86694. if (impostor.physicsBody) {
  86695. this.removePhysicsBody(impostor);
  86696. //TODO is that needed?
  86697. impostor.forceUpdate();
  86698. }
  86699. return;
  86700. }
  86701. if (impostor.isBodyInitRequired()) {
  86702. var bodyConfig = {
  86703. name: impostor.uniqueId,
  86704. //Oimo must have mass, also for static objects.
  86705. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86706. size: [],
  86707. type: [],
  86708. pos: [],
  86709. posShape: [],
  86710. rot: [],
  86711. rotShape: [],
  86712. move: impostor.getParam("mass") !== 0,
  86713. density: impostor.getParam("mass"),
  86714. friction: impostor.getParam("friction"),
  86715. restitution: impostor.getParam("restitution"),
  86716. //Supporting older versions of Oimo
  86717. world: this.world
  86718. };
  86719. var impostors = [impostor];
  86720. var addToArray = function (parent) {
  86721. if (!parent.getChildMeshes)
  86722. return;
  86723. parent.getChildMeshes().forEach(function (m) {
  86724. if (m.physicsImpostor) {
  86725. impostors.push(m.physicsImpostor);
  86726. //m.physicsImpostor._init();
  86727. }
  86728. });
  86729. };
  86730. addToArray(impostor.object);
  86731. var checkWithEpsilon_1 = function (value) {
  86732. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86733. };
  86734. impostors.forEach(function (i) {
  86735. if (!i.object.rotationQuaternion) {
  86736. return;
  86737. }
  86738. //get the correct bounding box
  86739. var oldQuaternion = i.object.rotationQuaternion;
  86740. var rot = oldQuaternion.toEulerAngles();
  86741. var extendSize = i.getObjectExtendSize();
  86742. var radToDeg = 57.295779513082320876;
  86743. if (i === impostor) {
  86744. var center = impostor.getObjectCenter();
  86745. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86746. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86747. //Can also use Array.prototype.push.apply
  86748. bodyConfig.pos.push(center.x);
  86749. bodyConfig.pos.push(center.y);
  86750. bodyConfig.pos.push(center.z);
  86751. bodyConfig.posShape.push(0, 0, 0);
  86752. //tmp solution
  86753. bodyConfig.rot.push(rot.x * radToDeg);
  86754. bodyConfig.rot.push(rot.y * radToDeg);
  86755. bodyConfig.rot.push(rot.z * radToDeg);
  86756. bodyConfig.rotShape.push(0, 0, 0);
  86757. }
  86758. else {
  86759. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86760. bodyConfig.posShape.push(localPosition.x);
  86761. bodyConfig.posShape.push(localPosition.y);
  86762. bodyConfig.posShape.push(localPosition.z);
  86763. bodyConfig.pos.push(0, 0, 0);
  86764. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86765. bodyConfig.rot.push(0);
  86766. bodyConfig.rot.push(0);
  86767. bodyConfig.rot.push(0);
  86768. bodyConfig.rotShape.push(rot.x * radToDeg);
  86769. bodyConfig.rotShape.push(rot.y * radToDeg);
  86770. bodyConfig.rotShape.push(rot.z * radToDeg);
  86771. }
  86772. // register mesh
  86773. switch (i.type) {
  86774. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86775. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86776. case BABYLON.PhysicsImpostor.SphereImpostor:
  86777. var radiusX = extendSize.x;
  86778. var radiusY = extendSize.y;
  86779. var radiusZ = extendSize.z;
  86780. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86781. bodyConfig.type.push('sphere');
  86782. //due to the way oimo works with compounds, add 3 times
  86783. bodyConfig.size.push(size);
  86784. bodyConfig.size.push(size);
  86785. bodyConfig.size.push(size);
  86786. break;
  86787. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86788. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86789. var sizeY = checkWithEpsilon_1(extendSize.y);
  86790. bodyConfig.type.push('cylinder');
  86791. bodyConfig.size.push(sizeX);
  86792. bodyConfig.size.push(sizeY);
  86793. //due to the way oimo works with compounds, add one more value.
  86794. bodyConfig.size.push(sizeY);
  86795. break;
  86796. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86797. case BABYLON.PhysicsImpostor.BoxImpostor:
  86798. default:
  86799. var sizeX = checkWithEpsilon_1(extendSize.x);
  86800. var sizeY = checkWithEpsilon_1(extendSize.y);
  86801. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86802. bodyConfig.type.push('box');
  86803. //if (i === impostor) {
  86804. bodyConfig.size.push(sizeX);
  86805. bodyConfig.size.push(sizeY);
  86806. bodyConfig.size.push(sizeZ);
  86807. //} else {
  86808. // bodyConfig.size.push(0,0,0);
  86809. //}
  86810. break;
  86811. }
  86812. //actually not needed, but hey...
  86813. i.object.rotationQuaternion = oldQuaternion;
  86814. });
  86815. impostor.physicsBody = this.world.add(bodyConfig);
  86816. }
  86817. else {
  86818. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86819. }
  86820. impostor.setDeltaPosition(this._tmpPositionVector);
  86821. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86822. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86823. };
  86824. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86825. //impostor.physicsBody.dispose();
  86826. //Same as : (older oimo versions)
  86827. this.world.removeRigidBody(impostor.physicsBody);
  86828. };
  86829. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86830. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86831. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86832. if (!mainBody || !connectedBody) {
  86833. return;
  86834. }
  86835. var jointData = impostorJoint.joint.jointData;
  86836. var options = jointData.nativeParams || {};
  86837. var type;
  86838. var nativeJointData = {
  86839. body1: mainBody,
  86840. body2: connectedBody,
  86841. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86842. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86843. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86844. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86845. min: options.min,
  86846. max: options.max,
  86847. collision: options.collision || jointData.collision,
  86848. spring: options.spring,
  86849. //supporting older version of Oimo
  86850. world: this.world
  86851. };
  86852. switch (impostorJoint.joint.type) {
  86853. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86854. type = "jointBall";
  86855. break;
  86856. case BABYLON.PhysicsJoint.SpringJoint:
  86857. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86858. var springData = jointData;
  86859. nativeJointData.min = springData.length || nativeJointData.min;
  86860. //Max should also be set, just make sure it is at least min
  86861. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86862. case BABYLON.PhysicsJoint.DistanceJoint:
  86863. type = "jointDistance";
  86864. nativeJointData.max = jointData.maxDistance;
  86865. break;
  86866. case BABYLON.PhysicsJoint.PrismaticJoint:
  86867. type = "jointPrisme";
  86868. break;
  86869. case BABYLON.PhysicsJoint.SliderJoint:
  86870. type = "jointSlide";
  86871. break;
  86872. case BABYLON.PhysicsJoint.WheelJoint:
  86873. type = "jointWheel";
  86874. break;
  86875. case BABYLON.PhysicsJoint.HingeJoint:
  86876. default:
  86877. type = "jointHinge";
  86878. break;
  86879. }
  86880. nativeJointData.type = type;
  86881. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86882. };
  86883. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86884. //Bug in Oimo prevents us from disposing a joint in the playground
  86885. //joint.joint.physicsJoint.dispose();
  86886. //So we will bruteforce it!
  86887. try {
  86888. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86889. }
  86890. catch (e) {
  86891. BABYLON.Tools.Warn(e);
  86892. }
  86893. };
  86894. OimoJSPlugin.prototype.isSupported = function () {
  86895. return this.BJSOIMO !== undefined;
  86896. };
  86897. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86898. if (!impostor.physicsBody.sleeping) {
  86899. //TODO check that
  86900. /*if (impostor.physicsBody.shapes.next) {
  86901. var parentShape = this._getLastShape(impostor.physicsBody);
  86902. impostor.object.position.copyFrom(parentShape.position);
  86903. console.log(parentShape.position);
  86904. } else {*/
  86905. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86906. //}
  86907. if (impostor.object.rotationQuaternion) {
  86908. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86909. }
  86910. }
  86911. };
  86912. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86913. var body = impostor.physicsBody;
  86914. body.position.copy(newPosition);
  86915. body.orientation.copy(newRotation);
  86916. body.syncShapes();
  86917. body.awake();
  86918. };
  86919. /*private _getLastShape(body: any): any {
  86920. var lastShape = body.shapes;
  86921. while (lastShape.next) {
  86922. lastShape = lastShape.next;
  86923. }
  86924. return lastShape;
  86925. }*/
  86926. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86927. impostor.physicsBody.linearVelocity.copy(velocity);
  86928. };
  86929. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86930. impostor.physicsBody.angularVelocity.copy(velocity);
  86931. };
  86932. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86933. var v = impostor.physicsBody.linearVelocity;
  86934. if (!v) {
  86935. return null;
  86936. }
  86937. return new BABYLON.Vector3(v.x, v.y, v.z);
  86938. };
  86939. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86940. var v = impostor.physicsBody.angularVelocity;
  86941. if (!v) {
  86942. return null;
  86943. }
  86944. return new BABYLON.Vector3(v.x, v.y, v.z);
  86945. };
  86946. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86947. var staticBody = mass === 0;
  86948. //this will actually set the body's density and not its mass.
  86949. //But this is how oimo treats the mass variable.
  86950. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86951. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86952. };
  86953. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86954. return impostor.physicsBody.shapes.density;
  86955. };
  86956. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86957. return impostor.physicsBody.shapes.friction;
  86958. };
  86959. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86960. impostor.physicsBody.shapes.friction = friction;
  86961. };
  86962. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86963. return impostor.physicsBody.shapes.restitution;
  86964. };
  86965. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86966. impostor.physicsBody.shapes.restitution = restitution;
  86967. };
  86968. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86969. impostor.physicsBody.sleep();
  86970. };
  86971. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86972. impostor.physicsBody.awake();
  86973. };
  86974. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86975. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86976. if (minDistance !== void 0) {
  86977. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86978. }
  86979. };
  86980. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86981. //TODO separate rotational and transational motors.
  86982. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86983. if (motor) {
  86984. motor.setMotor(speed, maxForce);
  86985. }
  86986. };
  86987. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86988. //TODO separate rotational and transational motors.
  86989. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86990. if (motor) {
  86991. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86992. }
  86993. };
  86994. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86995. var body = impostor.physicsBody;
  86996. mesh.position.x = body.position.x;
  86997. mesh.position.y = body.position.y;
  86998. mesh.position.z = body.position.z;
  86999. if (mesh.rotationQuaternion) {
  87000. mesh.rotationQuaternion.x = body.orientation.x;
  87001. mesh.rotationQuaternion.y = body.orientation.y;
  87002. mesh.rotationQuaternion.z = body.orientation.z;
  87003. mesh.rotationQuaternion.w = body.orientation.s;
  87004. }
  87005. };
  87006. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87007. return impostor.physicsBody.shapes.radius;
  87008. };
  87009. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87010. var shape = impostor.physicsBody.shapes;
  87011. result.x = shape.halfWidth * 2;
  87012. result.y = shape.halfHeight * 2;
  87013. result.z = shape.halfDepth * 2;
  87014. };
  87015. OimoJSPlugin.prototype.dispose = function () {
  87016. this.world.clear();
  87017. };
  87018. return OimoJSPlugin;
  87019. }());
  87020. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87021. })(BABYLON || (BABYLON = {}));
  87022. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87023. var BABYLON;
  87024. (function (BABYLON) {
  87025. /*
  87026. * Based on jsTGALoader - Javascript loader for TGA file
  87027. * By Vincent Thibault
  87028. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87029. */
  87030. var TGATools = /** @class */ (function () {
  87031. function TGATools() {
  87032. }
  87033. TGATools.GetTGAHeader = function (data) {
  87034. var offset = 0;
  87035. var header = {
  87036. id_length: data[offset++],
  87037. colormap_type: data[offset++],
  87038. image_type: data[offset++],
  87039. colormap_index: data[offset++] | data[offset++] << 8,
  87040. colormap_length: data[offset++] | data[offset++] << 8,
  87041. colormap_size: data[offset++],
  87042. origin: [
  87043. data[offset++] | data[offset++] << 8,
  87044. data[offset++] | data[offset++] << 8
  87045. ],
  87046. width: data[offset++] | data[offset++] << 8,
  87047. height: data[offset++] | data[offset++] << 8,
  87048. pixel_size: data[offset++],
  87049. flags: data[offset++]
  87050. };
  87051. return header;
  87052. };
  87053. TGATools.UploadContent = function (gl, data) {
  87054. // Not enough data to contain header ?
  87055. if (data.length < 19) {
  87056. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87057. return;
  87058. }
  87059. // Read Header
  87060. var offset = 18;
  87061. var header = TGATools.GetTGAHeader(data);
  87062. // Assume it's a valid Targa file.
  87063. if (header.id_length + offset > data.length) {
  87064. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87065. return;
  87066. }
  87067. // Skip not needed data
  87068. offset += header.id_length;
  87069. var use_rle = false;
  87070. var use_pal = false;
  87071. var use_grey = false;
  87072. // Get some informations.
  87073. switch (header.image_type) {
  87074. case TGATools._TYPE_RLE_INDEXED:
  87075. use_rle = true;
  87076. case TGATools._TYPE_INDEXED:
  87077. use_pal = true;
  87078. break;
  87079. case TGATools._TYPE_RLE_RGB:
  87080. use_rle = true;
  87081. case TGATools._TYPE_RGB:
  87082. // use_rgb = true;
  87083. break;
  87084. case TGATools._TYPE_RLE_GREY:
  87085. use_rle = true;
  87086. case TGATools._TYPE_GREY:
  87087. use_grey = true;
  87088. break;
  87089. }
  87090. var pixel_data;
  87091. // var numAlphaBits = header.flags & 0xf;
  87092. var pixel_size = header.pixel_size >> 3;
  87093. var pixel_total = header.width * header.height * pixel_size;
  87094. // Read palettes
  87095. var palettes;
  87096. if (use_pal) {
  87097. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87098. }
  87099. // Read LRE
  87100. if (use_rle) {
  87101. pixel_data = new Uint8Array(pixel_total);
  87102. var c, count, i;
  87103. var localOffset = 0;
  87104. var pixels = new Uint8Array(pixel_size);
  87105. while (offset < pixel_total && localOffset < pixel_total) {
  87106. c = data[offset++];
  87107. count = (c & 0x7f) + 1;
  87108. // RLE pixels
  87109. if (c & 0x80) {
  87110. // Bind pixel tmp array
  87111. for (i = 0; i < pixel_size; ++i) {
  87112. pixels[i] = data[offset++];
  87113. }
  87114. // Copy pixel array
  87115. for (i = 0; i < count; ++i) {
  87116. pixel_data.set(pixels, localOffset + i * pixel_size);
  87117. }
  87118. localOffset += pixel_size * count;
  87119. }
  87120. // Raw pixels
  87121. else {
  87122. count *= pixel_size;
  87123. for (i = 0; i < count; ++i) {
  87124. pixel_data[localOffset + i] = data[offset++];
  87125. }
  87126. localOffset += count;
  87127. }
  87128. }
  87129. }
  87130. // RAW Pixels
  87131. else {
  87132. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87133. }
  87134. // Load to texture
  87135. var x_start, y_start, x_step, y_step, y_end, x_end;
  87136. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87137. default:
  87138. case TGATools._ORIGIN_UL:
  87139. x_start = 0;
  87140. x_step = 1;
  87141. x_end = header.width;
  87142. y_start = 0;
  87143. y_step = 1;
  87144. y_end = header.height;
  87145. break;
  87146. case TGATools._ORIGIN_BL:
  87147. x_start = 0;
  87148. x_step = 1;
  87149. x_end = header.width;
  87150. y_start = header.height - 1;
  87151. y_step = -1;
  87152. y_end = -1;
  87153. break;
  87154. case TGATools._ORIGIN_UR:
  87155. x_start = header.width - 1;
  87156. x_step = -1;
  87157. x_end = -1;
  87158. y_start = 0;
  87159. y_step = 1;
  87160. y_end = header.height;
  87161. break;
  87162. case TGATools._ORIGIN_BR:
  87163. x_start = header.width - 1;
  87164. x_step = -1;
  87165. x_end = -1;
  87166. y_start = header.height - 1;
  87167. y_step = -1;
  87168. y_end = -1;
  87169. break;
  87170. }
  87171. // Load the specify method
  87172. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87173. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87174. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  87175. };
  87176. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87177. var image = pixel_data, colormap = palettes;
  87178. var width = header.width, height = header.height;
  87179. var color, i = 0, x, y;
  87180. var imageData = new Uint8Array(width * height * 4);
  87181. for (y = y_start; y !== y_end; y += y_step) {
  87182. for (x = x_start; x !== x_end; x += x_step, i++) {
  87183. color = image[i];
  87184. imageData[(x + width * y) * 4 + 3] = 255;
  87185. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87186. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87187. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87188. }
  87189. }
  87190. return imageData;
  87191. };
  87192. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87193. var image = pixel_data;
  87194. var width = header.width, height = header.height;
  87195. var color, i = 0, x, y;
  87196. var imageData = new Uint8Array(width * height * 4);
  87197. for (y = y_start; y !== y_end; y += y_step) {
  87198. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87199. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87200. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87201. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87202. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87203. imageData[(x + width * y) * 4 + 0] = r;
  87204. imageData[(x + width * y) * 4 + 1] = g;
  87205. imageData[(x + width * y) * 4 + 2] = b;
  87206. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87207. }
  87208. }
  87209. return imageData;
  87210. };
  87211. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87212. var image = pixel_data;
  87213. var width = header.width, height = header.height;
  87214. var i = 0, x, y;
  87215. var imageData = new Uint8Array(width * height * 4);
  87216. for (y = y_start; y !== y_end; y += y_step) {
  87217. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87218. imageData[(x + width * y) * 4 + 3] = 255;
  87219. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87220. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87221. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87222. }
  87223. }
  87224. return imageData;
  87225. };
  87226. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87227. var image = pixel_data;
  87228. var width = header.width, height = header.height;
  87229. var i = 0, x, y;
  87230. var imageData = new Uint8Array(width * height * 4);
  87231. for (y = y_start; y !== y_end; y += y_step) {
  87232. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87233. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87234. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87235. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87236. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87237. }
  87238. }
  87239. return imageData;
  87240. };
  87241. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87242. var image = pixel_data;
  87243. var width = header.width, height = header.height;
  87244. var color, i = 0, x, y;
  87245. var imageData = new Uint8Array(width * height * 4);
  87246. for (y = y_start; y !== y_end; y += y_step) {
  87247. for (x = x_start; x !== x_end; x += x_step, i++) {
  87248. color = image[i];
  87249. imageData[(x + width * y) * 4 + 0] = color;
  87250. imageData[(x + width * y) * 4 + 1] = color;
  87251. imageData[(x + width * y) * 4 + 2] = color;
  87252. imageData[(x + width * y) * 4 + 3] = 255;
  87253. }
  87254. }
  87255. return imageData;
  87256. };
  87257. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87258. var image = pixel_data;
  87259. var width = header.width, height = header.height;
  87260. var i = 0, x, y;
  87261. var imageData = new Uint8Array(width * height * 4);
  87262. for (y = y_start; y !== y_end; y += y_step) {
  87263. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87264. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87265. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87266. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87267. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87268. }
  87269. }
  87270. return imageData;
  87271. };
  87272. //private static _TYPE_NO_DATA = 0;
  87273. TGATools._TYPE_INDEXED = 1;
  87274. TGATools._TYPE_RGB = 2;
  87275. TGATools._TYPE_GREY = 3;
  87276. TGATools._TYPE_RLE_INDEXED = 9;
  87277. TGATools._TYPE_RLE_RGB = 10;
  87278. TGATools._TYPE_RLE_GREY = 11;
  87279. TGATools._ORIGIN_MASK = 0x30;
  87280. TGATools._ORIGIN_SHIFT = 0x04;
  87281. TGATools._ORIGIN_BL = 0x00;
  87282. TGATools._ORIGIN_BR = 0x01;
  87283. TGATools._ORIGIN_UL = 0x02;
  87284. TGATools._ORIGIN_UR = 0x03;
  87285. return TGATools;
  87286. }());
  87287. BABYLON.TGATools = TGATools;
  87288. })(BABYLON || (BABYLON = {}));
  87289. //# sourceMappingURL=babylon.tga.js.map
  87290. var BABYLON;
  87291. (function (BABYLON) {
  87292. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87293. // All values and structures referenced from:
  87294. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87295. var DDS_MAGIC = 0x20534444;
  87296. var
  87297. //DDSD_CAPS = 0x1,
  87298. //DDSD_HEIGHT = 0x2,
  87299. //DDSD_WIDTH = 0x4,
  87300. //DDSD_PITCH = 0x8,
  87301. //DDSD_PIXELFORMAT = 0x1000,
  87302. DDSD_MIPMAPCOUNT = 0x20000;
  87303. //DDSD_LINEARSIZE = 0x80000,
  87304. //DDSD_DEPTH = 0x800000;
  87305. // var DDSCAPS_COMPLEX = 0x8,
  87306. // DDSCAPS_MIPMAP = 0x400000,
  87307. // DDSCAPS_TEXTURE = 0x1000;
  87308. var DDSCAPS2_CUBEMAP = 0x200;
  87309. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87310. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87311. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87312. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87313. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87314. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87315. // DDSCAPS2_VOLUME = 0x200000;
  87316. var
  87317. //DDPF_ALPHAPIXELS = 0x1,
  87318. //DDPF_ALPHA = 0x2,
  87319. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87320. //DDPF_YUV = 0x200,
  87321. DDPF_LUMINANCE = 0x20000;
  87322. function FourCCToInt32(value) {
  87323. return value.charCodeAt(0) +
  87324. (value.charCodeAt(1) << 8) +
  87325. (value.charCodeAt(2) << 16) +
  87326. (value.charCodeAt(3) << 24);
  87327. }
  87328. function Int32ToFourCC(value) {
  87329. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87330. }
  87331. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87332. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87333. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87334. var FOURCC_DX10 = FourCCToInt32("DX10");
  87335. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87336. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87337. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87338. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87339. var headerLengthInt = 31; // The header length in 32 bit ints
  87340. // Offsets into the header array
  87341. var off_magic = 0;
  87342. var off_size = 1;
  87343. var off_flags = 2;
  87344. var off_height = 3;
  87345. var off_width = 4;
  87346. var off_mipmapCount = 7;
  87347. var off_pfFlags = 20;
  87348. var off_pfFourCC = 21;
  87349. var off_RGBbpp = 22;
  87350. var off_RMask = 23;
  87351. var off_GMask = 24;
  87352. var off_BMask = 25;
  87353. var off_AMask = 26;
  87354. // var off_caps1 = 27;
  87355. var off_caps2 = 28;
  87356. // var off_caps3 = 29;
  87357. // var off_caps4 = 30;
  87358. var off_dxgiFormat = 32;
  87359. ;
  87360. var DDSTools = /** @class */ (function () {
  87361. function DDSTools() {
  87362. }
  87363. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87364. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87365. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87366. var mipmapCount = 1;
  87367. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87368. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87369. }
  87370. var fourCC = header[off_pfFourCC];
  87371. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87372. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87373. switch (fourCC) {
  87374. case FOURCC_D3DFMT_R16G16B16A16F:
  87375. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87376. break;
  87377. case FOURCC_D3DFMT_R32G32B32A32F:
  87378. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87379. break;
  87380. case FOURCC_DX10:
  87381. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87382. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87383. break;
  87384. }
  87385. }
  87386. return {
  87387. width: header[off_width],
  87388. height: header[off_height],
  87389. mipmapCount: mipmapCount,
  87390. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87391. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87392. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87393. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87394. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87395. dxgiFormat: dxgiFormat,
  87396. textureType: textureType
  87397. };
  87398. };
  87399. DDSTools._ToHalfFloat = function (value) {
  87400. if (!DDSTools._FloatView) {
  87401. DDSTools._FloatView = new Float32Array(1);
  87402. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87403. }
  87404. DDSTools._FloatView[0] = value;
  87405. var x = DDSTools._Int32View[0];
  87406. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87407. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87408. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87409. /* If zero, or denormal, or exponent underflows too much for a denormal
  87410. * half, return signed zero. */
  87411. if (e < 103) {
  87412. return bits;
  87413. }
  87414. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87415. if (e > 142) {
  87416. bits |= 0x7c00;
  87417. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87418. * not Inf, so make sure we set one mantissa bit too. */
  87419. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87420. return bits;
  87421. }
  87422. /* If exponent underflows but not too much, return a denormal */
  87423. if (e < 113) {
  87424. m |= 0x0800;
  87425. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87426. * to 1, which is OK. */
  87427. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87428. return bits;
  87429. }
  87430. bits |= ((e - 112) << 10) | (m >> 1);
  87431. bits += m & 1;
  87432. return bits;
  87433. };
  87434. DDSTools._FromHalfFloat = function (value) {
  87435. var s = (value & 0x8000) >> 15;
  87436. var e = (value & 0x7C00) >> 10;
  87437. var f = value & 0x03FF;
  87438. if (e === 0) {
  87439. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87440. }
  87441. else if (e == 0x1F) {
  87442. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87443. }
  87444. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87445. };
  87446. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87447. var destArray = new Float32Array(dataLength);
  87448. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87449. var index = 0;
  87450. for (var y = 0; y < height; y++) {
  87451. for (var x = 0; x < width; x++) {
  87452. var srcPos = (x + y * width) * 4;
  87453. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87454. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87455. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87456. if (DDSTools.StoreLODInAlphaChannel) {
  87457. destArray[index + 3] = lod;
  87458. }
  87459. else {
  87460. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87461. }
  87462. index += 4;
  87463. }
  87464. }
  87465. return destArray;
  87466. };
  87467. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87468. if (DDSTools.StoreLODInAlphaChannel) {
  87469. var destArray = new Uint16Array(dataLength);
  87470. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87471. var index = 0;
  87472. for (var y = 0; y < height; y++) {
  87473. for (var x = 0; x < width; x++) {
  87474. var srcPos = (x + y * width) * 4;
  87475. destArray[index] = srcData[srcPos];
  87476. destArray[index + 1] = srcData[srcPos + 1];
  87477. destArray[index + 2] = srcData[srcPos + 2];
  87478. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87479. index += 4;
  87480. }
  87481. }
  87482. return destArray;
  87483. }
  87484. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87485. };
  87486. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87487. if (DDSTools.StoreLODInAlphaChannel) {
  87488. var destArray = new Float32Array(dataLength);
  87489. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87490. var index = 0;
  87491. for (var y = 0; y < height; y++) {
  87492. for (var x = 0; x < width; x++) {
  87493. var srcPos = (x + y * width) * 4;
  87494. destArray[index] = srcData[srcPos];
  87495. destArray[index + 1] = srcData[srcPos + 1];
  87496. destArray[index + 2] = srcData[srcPos + 2];
  87497. destArray[index + 3] = lod;
  87498. index += 4;
  87499. }
  87500. }
  87501. return destArray;
  87502. }
  87503. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87504. };
  87505. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87506. var destArray = new Uint8Array(dataLength);
  87507. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87508. var index = 0;
  87509. for (var y = 0; y < height; y++) {
  87510. for (var x = 0; x < width; x++) {
  87511. var srcPos = (x + y * width) * 4;
  87512. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87513. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87514. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87515. if (DDSTools.StoreLODInAlphaChannel) {
  87516. destArray[index + 3] = lod;
  87517. }
  87518. else {
  87519. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87520. }
  87521. index += 4;
  87522. }
  87523. }
  87524. return destArray;
  87525. };
  87526. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87527. var destArray = new Uint8Array(dataLength);
  87528. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87529. var index = 0;
  87530. for (var y = 0; y < height; y++) {
  87531. for (var x = 0; x < width; x++) {
  87532. var srcPos = (x + y * width) * 4;
  87533. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87534. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87535. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87536. if (DDSTools.StoreLODInAlphaChannel) {
  87537. destArray[index + 3] = lod;
  87538. }
  87539. else {
  87540. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87541. }
  87542. index += 4;
  87543. }
  87544. }
  87545. return destArray;
  87546. };
  87547. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87548. var byteArray = new Uint8Array(dataLength);
  87549. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87550. var index = 0;
  87551. for (var y = 0; y < height; y++) {
  87552. for (var x = 0; x < width; x++) {
  87553. var srcPos = (x + y * width) * 4;
  87554. byteArray[index] = srcData[srcPos + rOffset];
  87555. byteArray[index + 1] = srcData[srcPos + gOffset];
  87556. byteArray[index + 2] = srcData[srcPos + bOffset];
  87557. byteArray[index + 3] = srcData[srcPos + aOffset];
  87558. index += 4;
  87559. }
  87560. }
  87561. return byteArray;
  87562. };
  87563. DDSTools._ExtractLongWordOrder = function (value) {
  87564. if (value === 0 || value === 255 || value === -16777216) {
  87565. return 0;
  87566. }
  87567. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87568. };
  87569. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87570. var byteArray = new Uint8Array(dataLength);
  87571. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87572. var index = 0;
  87573. for (var y = 0; y < height; y++) {
  87574. for (var x = 0; x < width; x++) {
  87575. var srcPos = (x + y * width) * 3;
  87576. byteArray[index] = srcData[srcPos + rOffset];
  87577. byteArray[index + 1] = srcData[srcPos + gOffset];
  87578. byteArray[index + 2] = srcData[srcPos + bOffset];
  87579. index += 3;
  87580. }
  87581. }
  87582. return byteArray;
  87583. };
  87584. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87585. var byteArray = new Uint8Array(dataLength);
  87586. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87587. var index = 0;
  87588. for (var y = 0; y < height; y++) {
  87589. for (var x = 0; x < width; x++) {
  87590. var srcPos = (x + y * width);
  87591. byteArray[index] = srcData[srcPos];
  87592. index++;
  87593. }
  87594. }
  87595. return byteArray;
  87596. };
  87597. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87598. if (lodIndex === void 0) { lodIndex = -1; }
  87599. var sphericalPolynomialFaces = null;
  87600. if (info.sphericalPolynomial) {
  87601. sphericalPolynomialFaces = new Array();
  87602. }
  87603. var ext = engine.getCaps().s3tc;
  87604. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87605. var fourCC, width, height, dataLength = 0, dataOffset;
  87606. var byteArray, mipmapCount, mip;
  87607. var internalFormat = 0;
  87608. var format = 0;
  87609. var blockBytes = 1;
  87610. if (header[off_magic] !== DDS_MAGIC) {
  87611. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87612. return;
  87613. }
  87614. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87615. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87616. return;
  87617. }
  87618. if (info.isCompressed && !ext) {
  87619. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87620. return;
  87621. }
  87622. var bpp = header[off_RGBbpp];
  87623. dataOffset = header[off_size] + 4;
  87624. var computeFormats = false;
  87625. if (info.isFourCC) {
  87626. fourCC = header[off_pfFourCC];
  87627. switch (fourCC) {
  87628. case FOURCC_DXT1:
  87629. blockBytes = 8;
  87630. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87631. break;
  87632. case FOURCC_DXT3:
  87633. blockBytes = 16;
  87634. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87635. break;
  87636. case FOURCC_DXT5:
  87637. blockBytes = 16;
  87638. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87639. break;
  87640. case FOURCC_D3DFMT_R16G16B16A16F:
  87641. computeFormats = true;
  87642. break;
  87643. case FOURCC_D3DFMT_R32G32B32A32F:
  87644. computeFormats = true;
  87645. break;
  87646. case FOURCC_DX10:
  87647. // There is an additionnal header so dataOffset need to be changed
  87648. dataOffset += 5 * 4; // 5 uints
  87649. var supported = false;
  87650. switch (info.dxgiFormat) {
  87651. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87652. computeFormats = true;
  87653. supported = true;
  87654. break;
  87655. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87656. info.isRGB = true;
  87657. info.isFourCC = false;
  87658. bpp = 32;
  87659. supported = true;
  87660. break;
  87661. }
  87662. if (supported) {
  87663. break;
  87664. }
  87665. default:
  87666. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87667. return;
  87668. }
  87669. }
  87670. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87671. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87672. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87673. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87674. if (computeFormats) {
  87675. format = engine._getWebGLTextureType(info.textureType);
  87676. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87677. }
  87678. mipmapCount = 1;
  87679. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87680. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87681. }
  87682. for (var face = 0; face < faces; face++) {
  87683. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87684. width = header[off_width];
  87685. height = header[off_height];
  87686. for (mip = 0; mip < mipmapCount; ++mip) {
  87687. if (lodIndex === -1 || lodIndex === mip) {
  87688. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87689. var i = (lodIndex === -1) ? mip : 0;
  87690. if (!info.isCompressed && info.isFourCC) {
  87691. dataLength = width * height * 4;
  87692. var floatArray = null;
  87693. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87694. if (bpp === 128) {
  87695. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87696. if (sphericalPolynomialFaces && i == 0) {
  87697. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87698. }
  87699. }
  87700. else if (bpp === 64) {
  87701. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87702. if (sphericalPolynomialFaces && i == 0) {
  87703. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87704. }
  87705. }
  87706. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87707. format = engine._getWebGLTextureType(info.textureType);
  87708. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87709. }
  87710. else {
  87711. if (bpp === 128) {
  87712. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87713. if (sphericalPolynomialFaces && i == 0) {
  87714. sphericalPolynomialFaces.push(floatArray);
  87715. }
  87716. }
  87717. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87718. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87719. if (sphericalPolynomialFaces && i == 0) {
  87720. sphericalPolynomialFaces.push(floatArray);
  87721. }
  87722. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87723. format = engine._getWebGLTextureType(info.textureType);
  87724. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87725. }
  87726. else { // 64
  87727. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87728. if (sphericalPolynomialFaces && i == 0) {
  87729. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87730. }
  87731. }
  87732. }
  87733. if (floatArray) {
  87734. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87735. }
  87736. }
  87737. else if (info.isRGB) {
  87738. if (bpp === 24) {
  87739. dataLength = width * height * 3;
  87740. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87741. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87742. }
  87743. else { // 32
  87744. dataLength = width * height * 4;
  87745. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87746. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87747. }
  87748. }
  87749. else if (info.isLuminance) {
  87750. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87751. var unpaddedRowSize = width;
  87752. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87753. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87754. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87755. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87756. }
  87757. else {
  87758. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87759. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87760. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87761. }
  87762. }
  87763. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87764. width *= 0.5;
  87765. height *= 0.5;
  87766. width = Math.max(1.0, width);
  87767. height = Math.max(1.0, height);
  87768. }
  87769. if (currentFace !== undefined) {
  87770. // Loading a single face
  87771. break;
  87772. }
  87773. }
  87774. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87775. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87776. size: header[off_width],
  87777. right: sphericalPolynomialFaces[0],
  87778. left: sphericalPolynomialFaces[1],
  87779. up: sphericalPolynomialFaces[2],
  87780. down: sphericalPolynomialFaces[3],
  87781. front: sphericalPolynomialFaces[4],
  87782. back: sphericalPolynomialFaces[5],
  87783. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87784. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87785. gammaSpace: false,
  87786. });
  87787. }
  87788. else {
  87789. info.sphericalPolynomial = undefined;
  87790. }
  87791. };
  87792. DDSTools.StoreLODInAlphaChannel = false;
  87793. return DDSTools;
  87794. }());
  87795. BABYLON.DDSTools = DDSTools;
  87796. })(BABYLON || (BABYLON = {}));
  87797. //# sourceMappingURL=babylon.dds.js.map
  87798. var BABYLON;
  87799. (function (BABYLON) {
  87800. /**
  87801. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87802. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87803. */
  87804. var KhronosTextureContainer = /** @class */ (function () {
  87805. /**
  87806. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87807. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87808. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87809. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87810. */
  87811. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87812. this.arrayBuffer = arrayBuffer;
  87813. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87814. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87815. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87816. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87817. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87818. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87819. BABYLON.Tools.Error("texture missing KTX identifier");
  87820. return;
  87821. }
  87822. // load the reset of the header in native 32 bit int
  87823. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87824. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87825. var oppositeEndianess = header[0] === 0x01020304;
  87826. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87827. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87828. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87829. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87830. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87831. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87832. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87833. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87834. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87835. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87836. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87837. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87838. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87839. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87840. if (this.glType !== 0) {
  87841. BABYLON.Tools.Error("only compressed formats currently supported");
  87842. return;
  87843. }
  87844. else {
  87845. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87846. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87847. }
  87848. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87849. BABYLON.Tools.Error("only 2D textures currently supported");
  87850. return;
  87851. }
  87852. if (this.numberOfArrayElements !== 0) {
  87853. BABYLON.Tools.Error("texture arrays not currently supported");
  87854. return;
  87855. }
  87856. if (this.numberOfFaces !== facesExpected) {
  87857. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87858. return;
  87859. }
  87860. // we now have a completely validated file, so could use existence of loadType as success
  87861. // would need to make this more elaborate & adjust checks above to support more than one load type
  87862. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87863. }
  87864. // not as fast hardware based, but will probably never need to use
  87865. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87866. return ((val & 0xFF) << 24)
  87867. | ((val & 0xFF00) << 8)
  87868. | ((val >> 8) & 0xFF00)
  87869. | ((val >> 24) & 0xFF);
  87870. };
  87871. /**
  87872. * It is assumed that the texture has already been created & is currently bound
  87873. */
  87874. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87875. switch (this.loadType) {
  87876. case KhronosTextureContainer.COMPRESSED_2D:
  87877. this._upload2DCompressedLevels(gl, loadMipmaps);
  87878. break;
  87879. case KhronosTextureContainer.TEX_2D:
  87880. case KhronosTextureContainer.COMPRESSED_3D:
  87881. case KhronosTextureContainer.TEX_3D:
  87882. }
  87883. };
  87884. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87885. // initialize width & height for level 1
  87886. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87887. var width = this.pixelWidth;
  87888. var height = this.pixelHeight;
  87889. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87890. for (var level = 0; level < mipmapCount; level++) {
  87891. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87892. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87893. for (var face = 0; face < this.numberOfFaces; face++) {
  87894. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87895. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87896. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87897. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87898. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87899. }
  87900. width = Math.max(1.0, width * 0.5);
  87901. height = Math.max(1.0, height * 0.5);
  87902. }
  87903. };
  87904. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87905. // load types
  87906. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87907. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87908. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87909. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87910. return KhronosTextureContainer;
  87911. }());
  87912. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87913. })(BABYLON || (BABYLON = {}));
  87914. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87915. var BABYLON;
  87916. (function (BABYLON) {
  87917. var Debug;
  87918. (function (Debug) {
  87919. /**
  87920. * Class used to render a debug view of a given skeleton
  87921. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87922. */
  87923. var SkeletonViewer = /** @class */ (function () {
  87924. /**
  87925. * Creates a new SkeletonViewer
  87926. * @param skeleton defines the skeleton to render
  87927. * @param mesh defines the mesh attached to the skeleton
  87928. * @param scene defines the hosting scene
  87929. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87930. * @param renderingGroupId defines the rendering group id to use with the viewer
  87931. */
  87932. function SkeletonViewer(
  87933. /** defines the skeleton to render */
  87934. skeleton,
  87935. /** defines the mesh attached to the skeleton */
  87936. mesh, scene,
  87937. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87938. autoUpdateBonesMatrices,
  87939. /** defines the rendering group id to use with the viewer */
  87940. renderingGroupId) {
  87941. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87942. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87943. this.skeleton = skeleton;
  87944. this.mesh = mesh;
  87945. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87946. this.renderingGroupId = renderingGroupId;
  87947. /** Gets or sets the color used to render the skeleton */
  87948. this.color = BABYLON.Color3.White();
  87949. this._debugLines = new Array();
  87950. this._isEnabled = false;
  87951. this._scene = scene;
  87952. this.update();
  87953. this._renderFunction = this.update.bind(this);
  87954. }
  87955. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87956. get: function () {
  87957. return this._isEnabled;
  87958. },
  87959. /** Gets or sets a boolean indicating if the viewer is enabled */
  87960. set: function (value) {
  87961. if (this._isEnabled === value) {
  87962. return;
  87963. }
  87964. this._isEnabled = value;
  87965. if (value) {
  87966. this._scene.registerBeforeRender(this._renderFunction);
  87967. }
  87968. else {
  87969. this._scene.unregisterBeforeRender(this._renderFunction);
  87970. }
  87971. },
  87972. enumerable: true,
  87973. configurable: true
  87974. });
  87975. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87976. if (x === void 0) { x = 0; }
  87977. if (y === void 0) { y = 0; }
  87978. if (z === void 0) { z = 0; }
  87979. var tmat = BABYLON.Tmp.Matrix[0];
  87980. var parentBone = bone.getParent();
  87981. tmat.copyFrom(bone.getLocalMatrix());
  87982. if (x !== 0 || y !== 0 || z !== 0) {
  87983. var tmat2 = BABYLON.Tmp.Matrix[1];
  87984. BABYLON.Matrix.IdentityToRef(tmat2);
  87985. tmat2.m[12] = x;
  87986. tmat2.m[13] = y;
  87987. tmat2.m[14] = z;
  87988. tmat2.multiplyToRef(tmat, tmat);
  87989. }
  87990. if (parentBone) {
  87991. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87992. }
  87993. tmat.multiplyToRef(meshMat, tmat);
  87994. position.x = tmat.m[12];
  87995. position.y = tmat.m[13];
  87996. position.z = tmat.m[14];
  87997. };
  87998. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87999. var len = bones.length;
  88000. var meshPos = this.mesh.position;
  88001. for (var i = 0; i < len; i++) {
  88002. var bone = bones[i];
  88003. var points = this._debugLines[i];
  88004. if (!points) {
  88005. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88006. this._debugLines[i] = points;
  88007. }
  88008. this._getBonePosition(points[0], bone, meshMat);
  88009. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  88010. points[0].subtractInPlace(meshPos);
  88011. points[1].subtractInPlace(meshPos);
  88012. }
  88013. };
  88014. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  88015. var len = bones.length;
  88016. var boneNum = 0;
  88017. var meshPos = this.mesh.position;
  88018. for (var i = len - 1; i >= 0; i--) {
  88019. var childBone = bones[i];
  88020. var parentBone = childBone.getParent();
  88021. if (!parentBone) {
  88022. continue;
  88023. }
  88024. var points = this._debugLines[boneNum];
  88025. if (!points) {
  88026. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88027. this._debugLines[boneNum] = points;
  88028. }
  88029. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  88030. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  88031. points[0].subtractInPlace(meshPos);
  88032. points[1].subtractInPlace(meshPos);
  88033. boneNum++;
  88034. }
  88035. };
  88036. /** Update the viewer to sync with current skeleton state */
  88037. SkeletonViewer.prototype.update = function () {
  88038. if (this.autoUpdateBonesMatrices) {
  88039. this.skeleton.computeAbsoluteTransforms();
  88040. }
  88041. if (this.skeleton.bones[0].length === undefined) {
  88042. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88043. }
  88044. else {
  88045. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88046. }
  88047. if (!this._debugMesh) {
  88048. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  88049. this._debugMesh.renderingGroupId = this.renderingGroupId;
  88050. }
  88051. else {
  88052. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  88053. }
  88054. this._debugMesh.position.copyFrom(this.mesh.position);
  88055. this._debugMesh.color = this.color;
  88056. };
  88057. /** Release associated resources */
  88058. SkeletonViewer.prototype.dispose = function () {
  88059. if (this._debugMesh) {
  88060. this.isEnabled = false;
  88061. this._debugMesh.dispose();
  88062. this._debugMesh = null;
  88063. }
  88064. };
  88065. return SkeletonViewer;
  88066. }());
  88067. Debug.SkeletonViewer = SkeletonViewer;
  88068. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88069. })(BABYLON || (BABYLON = {}));
  88070. //# sourceMappingURL=babylon.skeletonViewer.js.map
  88071. /**
  88072. * Module Debug contains the (visual) components to debug a scene correctly
  88073. */
  88074. var BABYLON;
  88075. (function (BABYLON) {
  88076. var Debug;
  88077. (function (Debug) {
  88078. /**
  88079. * The Axes viewer will show 3 axes in a specific point in space
  88080. */
  88081. var AxesViewer = /** @class */ (function () {
  88082. /**
  88083. * Creates a new AxesViewer
  88084. * @param scene defines the hosting scene
  88085. * @param scaleLines defines a number used to scale line length (1 by default)
  88086. */
  88087. function AxesViewer(scene, scaleLines) {
  88088. if (scaleLines === void 0) { scaleLines = 1; }
  88089. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88090. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88091. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88092. /**
  88093. * Gets or sets a number used to scale line length
  88094. */
  88095. this.scaleLines = 1;
  88096. this.scaleLines = scaleLines;
  88097. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  88098. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  88099. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  88100. this._xmesh.renderingGroupId = 2;
  88101. this._ymesh.renderingGroupId = 2;
  88102. this._zmesh.renderingGroupId = 2;
  88103. this._xmesh.material.checkReadyOnlyOnce = true;
  88104. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  88105. this._ymesh.material.checkReadyOnlyOnce = true;
  88106. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  88107. this._zmesh.material.checkReadyOnlyOnce = true;
  88108. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  88109. this.scene = scene;
  88110. }
  88111. /**
  88112. * Force the viewer to update
  88113. * @param position defines the position of the viewer
  88114. * @param xaxis defines the x axis of the viewer
  88115. * @param yaxis defines the y axis of the viewer
  88116. * @param zaxis defines the z axis of the viewer
  88117. */
  88118. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  88119. var scaleLines = this.scaleLines;
  88120. if (this._xmesh) {
  88121. this._xmesh.position.copyFrom(position);
  88122. }
  88123. if (this._ymesh) {
  88124. this._ymesh.position.copyFrom(position);
  88125. }
  88126. if (this._zmesh) {
  88127. this._zmesh.position.copyFrom(position);
  88128. }
  88129. var point2 = this._xline[1];
  88130. point2.x = xaxis.x * scaleLines;
  88131. point2.y = xaxis.y * scaleLines;
  88132. point2.z = xaxis.z * scaleLines;
  88133. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  88134. point2 = this._yline[1];
  88135. point2.x = yaxis.x * scaleLines;
  88136. point2.y = yaxis.y * scaleLines;
  88137. point2.z = yaxis.z * scaleLines;
  88138. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  88139. point2 = this._zline[1];
  88140. point2.x = zaxis.x * scaleLines;
  88141. point2.y = zaxis.y * scaleLines;
  88142. point2.z = zaxis.z * scaleLines;
  88143. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  88144. };
  88145. /** Releases resources */
  88146. AxesViewer.prototype.dispose = function () {
  88147. if (this._xmesh) {
  88148. this._xmesh.dispose();
  88149. }
  88150. if (this._ymesh) {
  88151. this._ymesh.dispose();
  88152. }
  88153. if (this._zmesh) {
  88154. this._zmesh.dispose();
  88155. }
  88156. this._xmesh = null;
  88157. this._ymesh = null;
  88158. this._zmesh = null;
  88159. this.scene = null;
  88160. };
  88161. return AxesViewer;
  88162. }());
  88163. Debug.AxesViewer = AxesViewer;
  88164. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88165. })(BABYLON || (BABYLON = {}));
  88166. //# sourceMappingURL=babylon.axesViewer.js.map
  88167. var BABYLON;
  88168. (function (BABYLON) {
  88169. var Debug;
  88170. (function (Debug) {
  88171. /**
  88172. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  88173. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  88174. */
  88175. var BoneAxesViewer = /** @class */ (function (_super) {
  88176. __extends(BoneAxesViewer, _super);
  88177. /**
  88178. * Creates a new BoneAxesViewer
  88179. * @param scene defines the hosting scene
  88180. * @param bone defines the target bone
  88181. * @param mesh defines the target mesh
  88182. * @param scaleLines defines a scaling factor for line length (1 by default)
  88183. */
  88184. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  88185. if (scaleLines === void 0) { scaleLines = 1; }
  88186. var _this = _super.call(this, scene, scaleLines) || this;
  88187. /** Gets current position */
  88188. _this.pos = BABYLON.Vector3.Zero();
  88189. /** Gets direction of X axis */
  88190. _this.xaxis = BABYLON.Vector3.Zero();
  88191. /** Gets direction of Y axis */
  88192. _this.yaxis = BABYLON.Vector3.Zero();
  88193. /** Gets direction of Z axis */
  88194. _this.zaxis = BABYLON.Vector3.Zero();
  88195. _this.mesh = mesh;
  88196. _this.bone = bone;
  88197. return _this;
  88198. }
  88199. /**
  88200. * Force the viewer to update
  88201. */
  88202. BoneAxesViewer.prototype.update = function () {
  88203. if (!this.mesh || !this.bone) {
  88204. return;
  88205. }
  88206. var bone = this.bone;
  88207. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  88208. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  88209. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  88210. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  88211. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  88212. };
  88213. /** Releases resources */
  88214. BoneAxesViewer.prototype.dispose = function () {
  88215. if (this.mesh) {
  88216. this.mesh = null;
  88217. this.bone = null;
  88218. _super.prototype.dispose.call(this);
  88219. }
  88220. };
  88221. return BoneAxesViewer;
  88222. }(Debug.AxesViewer));
  88223. Debug.BoneAxesViewer = BoneAxesViewer;
  88224. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88225. })(BABYLON || (BABYLON = {}));
  88226. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88227. var BABYLON;
  88228. (function (BABYLON) {
  88229. var RayHelper = /** @class */ (function () {
  88230. function RayHelper(ray) {
  88231. this.ray = ray;
  88232. }
  88233. RayHelper.CreateAndShow = function (ray, scene, color) {
  88234. var helper = new RayHelper(ray);
  88235. helper.show(scene, color);
  88236. return helper;
  88237. };
  88238. RayHelper.prototype.show = function (scene, color) {
  88239. if (!this._renderFunction && this.ray) {
  88240. var ray = this.ray;
  88241. this._renderFunction = this._render.bind(this);
  88242. this._scene = scene;
  88243. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88244. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88245. if (this._renderFunction) {
  88246. this._scene.registerBeforeRender(this._renderFunction);
  88247. }
  88248. }
  88249. if (color && this._renderLine) {
  88250. this._renderLine.color.copyFrom(color);
  88251. }
  88252. };
  88253. RayHelper.prototype.hide = function () {
  88254. if (this._renderFunction && this._scene) {
  88255. this._scene.unregisterBeforeRender(this._renderFunction);
  88256. this._scene = null;
  88257. this._renderFunction = null;
  88258. if (this._renderLine) {
  88259. this._renderLine.dispose();
  88260. this._renderLine = null;
  88261. }
  88262. this._renderPoints = [];
  88263. }
  88264. };
  88265. RayHelper.prototype._render = function () {
  88266. var ray = this.ray;
  88267. if (!ray) {
  88268. return;
  88269. }
  88270. var point = this._renderPoints[1];
  88271. var len = Math.min(ray.length, 1000000);
  88272. point.copyFrom(ray.direction);
  88273. point.scaleInPlace(len);
  88274. point.addInPlace(ray.origin);
  88275. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88276. };
  88277. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88278. this._attachedToMesh = mesh;
  88279. var ray = this.ray;
  88280. if (!ray) {
  88281. return;
  88282. }
  88283. if (!ray.direction) {
  88284. ray.direction = BABYLON.Vector3.Zero();
  88285. }
  88286. if (!ray.origin) {
  88287. ray.origin = BABYLON.Vector3.Zero();
  88288. }
  88289. if (length) {
  88290. ray.length = length;
  88291. }
  88292. if (!meshSpaceOrigin) {
  88293. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88294. }
  88295. if (!meshSpaceDirection) {
  88296. // -1 so that this will work with Mesh.lookAt
  88297. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88298. }
  88299. if (!this._meshSpaceDirection) {
  88300. this._meshSpaceDirection = meshSpaceDirection.clone();
  88301. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88302. }
  88303. else {
  88304. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88305. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88306. }
  88307. if (!this._updateToMeshFunction) {
  88308. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88309. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88310. }
  88311. this._updateToMesh();
  88312. };
  88313. RayHelper.prototype.detachFromMesh = function () {
  88314. if (this._attachedToMesh) {
  88315. if (this._updateToMeshFunction) {
  88316. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88317. }
  88318. this._attachedToMesh = null;
  88319. this._updateToMeshFunction = null;
  88320. }
  88321. };
  88322. RayHelper.prototype._updateToMesh = function () {
  88323. var ray = this.ray;
  88324. if (!this._attachedToMesh || !ray) {
  88325. return;
  88326. }
  88327. if (this._attachedToMesh._isDisposed) {
  88328. this.detachFromMesh();
  88329. return;
  88330. }
  88331. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88332. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88333. };
  88334. RayHelper.prototype.dispose = function () {
  88335. this.hide();
  88336. this.detachFromMesh();
  88337. this.ray = null;
  88338. };
  88339. return RayHelper;
  88340. }());
  88341. BABYLON.RayHelper = RayHelper;
  88342. })(BABYLON || (BABYLON = {}));
  88343. //# sourceMappingURL=babylon.rayHelper.js.map
  88344. var BABYLON;
  88345. (function (BABYLON) {
  88346. // load the inspector using require, if not present in the global namespace.
  88347. var DebugLayer = /** @class */ (function () {
  88348. function DebugLayer(scene) {
  88349. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88350. this._scene = scene;
  88351. // load inspector using require, if it doesn't exist on the global namespace.
  88352. }
  88353. /** Creates the inspector window. */
  88354. DebugLayer.prototype._createInspector = function (config) {
  88355. if (config === void 0) { config = {}; }
  88356. var popup = config.popup || false;
  88357. var initialTab = config.initialTab || 0;
  88358. var parentElement = config.parentElement || null;
  88359. if (!this._inspector) {
  88360. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88361. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88362. } // else nothing to do,; instance is already existing
  88363. };
  88364. DebugLayer.prototype.isVisible = function () {
  88365. if (!this._inspector) {
  88366. return false;
  88367. }
  88368. return true;
  88369. };
  88370. DebugLayer.prototype.hide = function () {
  88371. if (this._inspector) {
  88372. try {
  88373. this._inspector.dispose();
  88374. }
  88375. catch (e) {
  88376. // If the inspector has been removed directly from the inspector tool
  88377. }
  88378. this.onPropertyChangedObservable.clear();
  88379. this._inspector = null;
  88380. }
  88381. };
  88382. /**
  88383. *
  88384. * Launch the debugLayer.
  88385. *
  88386. * initialTab:
  88387. * | Value | Tab Name |
  88388. * | --- | --- |
  88389. * | 0 | Scene |
  88390. * | 1 | Console |
  88391. * | 2 | Stats |
  88392. * | 3 | Textures |
  88393. * | 4 | Mesh |
  88394. * | 5 | Light |
  88395. * | 6 | Material |
  88396. * | 7 | GLTF |
  88397. * | 8 | GUI |
  88398. * | 9 | Physics |
  88399. * | 10 | Camera |
  88400. * | 11 | Audio |
  88401. *
  88402. */
  88403. DebugLayer.prototype.show = function (config) {
  88404. if (config === void 0) { config = {}; }
  88405. if (typeof this.BJSINSPECTOR == 'undefined') {
  88406. // Load inspector and add it to the DOM
  88407. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88408. }
  88409. else {
  88410. // Otherwise creates the inspector
  88411. this._createInspector(config);
  88412. this.onPropertyChangedObservable = new BABYLON.Observable();
  88413. }
  88414. };
  88415. /**
  88416. * Gets the active tab
  88417. * @return the index of the active tab or -1 if the inspector is hidden
  88418. */
  88419. DebugLayer.prototype.getActiveTab = function () {
  88420. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88421. };
  88422. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88423. return DebugLayer;
  88424. }());
  88425. BABYLON.DebugLayer = DebugLayer;
  88426. })(BABYLON || (BABYLON = {}));
  88427. //# sourceMappingURL=babylon.debugLayer.js.map
  88428. var BABYLON;
  88429. (function (BABYLON) {
  88430. var Debug;
  88431. (function (Debug) {
  88432. /**
  88433. * Used to show the physics impostor around the specific mesh
  88434. */
  88435. var PhysicsViewer = /** @class */ (function () {
  88436. /**
  88437. * Creates a new PhysicsViewer
  88438. * @param scene defines the hosting scene
  88439. */
  88440. function PhysicsViewer(scene) {
  88441. /** @hidden */
  88442. this._impostors = [];
  88443. /** @hidden */
  88444. this._meshes = [];
  88445. /** @hidden */
  88446. this._numMeshes = 0;
  88447. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88448. var physicEngine = this._scene.getPhysicsEngine();
  88449. if (physicEngine) {
  88450. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88451. }
  88452. }
  88453. /** @hidden */
  88454. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88455. var plugin = this._physicsEnginePlugin;
  88456. for (var i = 0; i < this._numMeshes; i++) {
  88457. var impostor = this._impostors[i];
  88458. if (!impostor) {
  88459. continue;
  88460. }
  88461. if (impostor.isDisposed) {
  88462. this.hideImpostor(this._impostors[i--]);
  88463. }
  88464. else {
  88465. var mesh = this._meshes[i];
  88466. if (mesh && plugin) {
  88467. plugin.syncMeshWithImpostor(mesh, impostor);
  88468. }
  88469. }
  88470. }
  88471. };
  88472. /**
  88473. * Renders a specified physic impostor
  88474. * @param impostor defines the impostor to render
  88475. */
  88476. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88477. if (!this._scene) {
  88478. return;
  88479. }
  88480. for (var i = 0; i < this._numMeshes; i++) {
  88481. if (this._impostors[i] == impostor) {
  88482. return;
  88483. }
  88484. }
  88485. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88486. if (debugMesh) {
  88487. this._impostors[this._numMeshes] = impostor;
  88488. this._meshes[this._numMeshes] = debugMesh;
  88489. if (this._numMeshes === 0) {
  88490. this._renderFunction = this._updateDebugMeshes.bind(this);
  88491. this._scene.registerBeforeRender(this._renderFunction);
  88492. }
  88493. this._numMeshes++;
  88494. }
  88495. };
  88496. /**
  88497. * Hides a specified physic impostor
  88498. * @param impostor defines the impostor to hide
  88499. */
  88500. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88501. if (!impostor || !this._scene) {
  88502. return;
  88503. }
  88504. var removed = false;
  88505. for (var i = 0; i < this._numMeshes; i++) {
  88506. if (this._impostors[i] == impostor) {
  88507. var mesh = this._meshes[i];
  88508. if (!mesh) {
  88509. continue;
  88510. }
  88511. this._scene.removeMesh(mesh);
  88512. mesh.dispose();
  88513. this._numMeshes--;
  88514. if (this._numMeshes > 0) {
  88515. this._meshes[i] = this._meshes[this._numMeshes];
  88516. this._impostors[i] = this._impostors[this._numMeshes];
  88517. this._meshes[this._numMeshes] = null;
  88518. this._impostors[this._numMeshes] = null;
  88519. }
  88520. else {
  88521. this._meshes[0] = null;
  88522. this._impostors[0] = null;
  88523. }
  88524. removed = true;
  88525. break;
  88526. }
  88527. }
  88528. if (removed && this._numMeshes === 0) {
  88529. this._scene.unregisterBeforeRender(this._renderFunction);
  88530. }
  88531. };
  88532. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88533. if (!this._debugMaterial) {
  88534. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88535. this._debugMaterial.wireframe = true;
  88536. }
  88537. return this._debugMaterial;
  88538. };
  88539. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88540. if (!this._debugBoxMesh) {
  88541. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88542. this._debugBoxMesh.renderingGroupId = 1;
  88543. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88544. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88545. scene.removeMesh(this._debugBoxMesh);
  88546. }
  88547. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88548. };
  88549. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88550. if (!this._debugSphereMesh) {
  88551. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88552. this._debugSphereMesh.renderingGroupId = 1;
  88553. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88554. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88555. scene.removeMesh(this._debugSphereMesh);
  88556. }
  88557. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88558. };
  88559. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88560. var mesh = null;
  88561. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88562. mesh = this._getDebugBoxMesh(scene);
  88563. impostor.getBoxSizeToRef(mesh.scaling);
  88564. }
  88565. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88566. mesh = this._getDebugSphereMesh(scene);
  88567. var radius = impostor.getRadius();
  88568. mesh.scaling.x = radius * 2;
  88569. mesh.scaling.y = radius * 2;
  88570. mesh.scaling.z = radius * 2;
  88571. }
  88572. return mesh;
  88573. };
  88574. /** Releases all resources */
  88575. PhysicsViewer.prototype.dispose = function () {
  88576. for (var i = 0; i < this._numMeshes; i++) {
  88577. this.hideImpostor(this._impostors[i]);
  88578. }
  88579. if (this._debugBoxMesh) {
  88580. this._debugBoxMesh.dispose();
  88581. }
  88582. if (this._debugSphereMesh) {
  88583. this._debugSphereMesh.dispose();
  88584. }
  88585. if (this._debugMaterial) {
  88586. this._debugMaterial.dispose();
  88587. }
  88588. this._impostors.length = 0;
  88589. this._scene = null;
  88590. this._physicsEnginePlugin = null;
  88591. };
  88592. return PhysicsViewer;
  88593. }());
  88594. Debug.PhysicsViewer = PhysicsViewer;
  88595. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88596. })(BABYLON || (BABYLON = {}));
  88597. //# sourceMappingURL=babylon.physicsViewer.js.map
  88598. var BABYLON;
  88599. (function (BABYLON) {
  88600. var BoundingBoxRenderer = /** @class */ (function () {
  88601. function BoundingBoxRenderer(scene) {
  88602. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88603. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88604. this.showBackLines = true;
  88605. this.renderList = new BABYLON.SmartArray(32);
  88606. this._vertexBuffers = {};
  88607. this._scene = scene;
  88608. }
  88609. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88610. if (this._colorShader) {
  88611. return;
  88612. }
  88613. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88614. attributes: [BABYLON.VertexBuffer.PositionKind],
  88615. uniforms: ["world", "viewProjection", "color"]
  88616. });
  88617. var engine = this._scene.getEngine();
  88618. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88619. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88620. this._createIndexBuffer();
  88621. };
  88622. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88623. var engine = this._scene.getEngine();
  88624. 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]);
  88625. };
  88626. BoundingBoxRenderer.prototype._rebuild = function () {
  88627. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88628. if (vb) {
  88629. vb._rebuild();
  88630. }
  88631. this._createIndexBuffer();
  88632. };
  88633. BoundingBoxRenderer.prototype.reset = function () {
  88634. this.renderList.reset();
  88635. };
  88636. BoundingBoxRenderer.prototype.render = function () {
  88637. if (this.renderList.length === 0) {
  88638. return;
  88639. }
  88640. this._prepareRessources();
  88641. if (!this._colorShader.isReady()) {
  88642. return;
  88643. }
  88644. var engine = this._scene.getEngine();
  88645. engine.setDepthWrite(false);
  88646. this._colorShader._preBind();
  88647. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88648. var boundingBox = this.renderList.data[boundingBoxIndex];
  88649. var min = boundingBox.minimum;
  88650. var max = boundingBox.maximum;
  88651. var diff = max.subtract(min);
  88652. var median = min.add(diff.scale(0.5));
  88653. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88654. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88655. .multiply(boundingBox.getWorldMatrix());
  88656. // VBOs
  88657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88658. if (this.showBackLines) {
  88659. // Back
  88660. engine.setDepthFunctionToGreaterOrEqual();
  88661. this._scene.resetCachedMaterial();
  88662. this._colorShader.setColor4("color", this.backColor.toColor4());
  88663. this._colorShader.bind(worldMatrix);
  88664. // Draw order
  88665. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88666. }
  88667. // Front
  88668. engine.setDepthFunctionToLess();
  88669. this._scene.resetCachedMaterial();
  88670. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88671. this._colorShader.bind(worldMatrix);
  88672. // Draw order
  88673. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88674. }
  88675. this._colorShader.unbind();
  88676. engine.setDepthFunctionToLessOrEqual();
  88677. engine.setDepthWrite(true);
  88678. };
  88679. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88680. this._prepareRessources();
  88681. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88682. return;
  88683. }
  88684. var engine = this._scene.getEngine();
  88685. engine.setDepthWrite(false);
  88686. engine.setColorWrite(false);
  88687. this._colorShader._preBind();
  88688. var boundingBox = mesh._boundingInfo.boundingBox;
  88689. var min = boundingBox.minimum;
  88690. var max = boundingBox.maximum;
  88691. var diff = max.subtract(min);
  88692. var median = min.add(diff.scale(0.5));
  88693. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88694. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88695. .multiply(boundingBox.getWorldMatrix());
  88696. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88697. engine.setDepthFunctionToLess();
  88698. this._scene.resetCachedMaterial();
  88699. this._colorShader.bind(worldMatrix);
  88700. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88701. this._colorShader.unbind();
  88702. engine.setDepthFunctionToLessOrEqual();
  88703. engine.setDepthWrite(true);
  88704. engine.setColorWrite(true);
  88705. };
  88706. BoundingBoxRenderer.prototype.dispose = function () {
  88707. if (!this._colorShader) {
  88708. return;
  88709. }
  88710. this.renderList.dispose();
  88711. this._colorShader.dispose();
  88712. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88713. if (buffer) {
  88714. buffer.dispose();
  88715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88716. }
  88717. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88718. };
  88719. return BoundingBoxRenderer;
  88720. }());
  88721. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88722. })(BABYLON || (BABYLON = {}));
  88723. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88724. var BABYLON;
  88725. (function (BABYLON) {
  88726. /**
  88727. * Renders a layer on top of an existing scene
  88728. */
  88729. var UtilityLayerRenderer = /** @class */ (function () {
  88730. /**
  88731. * Instantiates a UtilityLayerRenderer
  88732. * @param originalScene the original scene that will be rendered on top of
  88733. */
  88734. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88735. var _this = this;
  88736. this.originalScene = originalScene;
  88737. this._pointerCaptures = {};
  88738. this._lastPointerEvents = {};
  88739. /**
  88740. * If the utility layer should automatically be rendered on top of existing scene
  88741. */
  88742. this.shouldRender = true;
  88743. /**
  88744. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88745. */
  88746. this.onlyCheckPointerDownEvents = true;
  88747. /**
  88748. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88749. */
  88750. this.processAllEvents = false;
  88751. /**
  88752. * Observable raised when the pointer move from the utility layer scene to the main scene
  88753. */
  88754. this.onPointerOutObservable = new BABYLON.Observable();
  88755. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88756. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88757. originalScene.getEngine().scenes.pop();
  88758. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88759. this.utilityLayerScene.detachControl();
  88760. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88761. if (!_this.processAllEvents) {
  88762. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88763. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88764. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88765. return;
  88766. }
  88767. }
  88768. var pointerEvent = (prePointerInfo.event);
  88769. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88770. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88771. return;
  88772. }
  88773. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88774. if (!prePointerInfo.ray && utilityScenePick) {
  88775. prePointerInfo.ray = utilityScenePick.ray;
  88776. }
  88777. // always fire the prepointer oversvable
  88778. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88779. // allow every non pointer down event to flow to the utility layer
  88780. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88781. if (!prePointerInfo.skipOnPointerObservable) {
  88782. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88783. }
  88784. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88785. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88786. }
  88787. return;
  88788. }
  88789. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88790. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88791. if (utilityScenePick && utilityScenePick.hit) {
  88792. if (!prePointerInfo.skipOnPointerObservable) {
  88793. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88794. }
  88795. prePointerInfo.skipOnPointerObservable = true;
  88796. }
  88797. }
  88798. else {
  88799. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88800. var pointerEvent_1 = (prePointerInfo.event);
  88801. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88802. if (originalScenePick && utilityScenePick) {
  88803. // No pick in utility scene
  88804. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88805. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88806. // We touched an utility mesh present in the main scene
  88807. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88808. prePointerInfo.skipOnPointerObservable = true;
  88809. }
  88810. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88811. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88812. }
  88813. }
  88814. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88815. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88816. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88817. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88818. }
  88819. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88820. // We have a pick in both scenes but main is closer than utility
  88821. // We touched an utility mesh present in the main scene
  88822. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88823. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88824. prePointerInfo.skipOnPointerObservable = true;
  88825. }
  88826. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88827. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88828. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88829. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88830. }
  88831. }
  88832. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88833. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88834. }
  88835. }
  88836. }
  88837. });
  88838. // Render directly on top of existing scene without clearing
  88839. this.utilityLayerScene.autoClear = false;
  88840. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88841. if (_this.shouldRender) {
  88842. _this.render();
  88843. }
  88844. });
  88845. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88846. _this.dispose();
  88847. });
  88848. this._updateCamera();
  88849. }
  88850. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88851. get: function () {
  88852. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88853. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88854. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88855. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88856. });
  88857. }
  88858. return UtilityLayerRenderer._DefaultUtilityLayer;
  88859. },
  88860. enumerable: true,
  88861. configurable: true
  88862. });
  88863. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88864. if (!prePointerInfo.skipOnPointerObservable) {
  88865. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88866. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88867. }
  88868. };
  88869. /**
  88870. * Renders the utility layers scene on top of the original scene
  88871. */
  88872. UtilityLayerRenderer.prototype.render = function () {
  88873. this._updateCamera();
  88874. this.utilityLayerScene.render(false);
  88875. };
  88876. /**
  88877. * Disposes of the renderer
  88878. */
  88879. UtilityLayerRenderer.prototype.dispose = function () {
  88880. this.onPointerOutObservable.clear();
  88881. if (this._afterRenderObserver) {
  88882. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88883. }
  88884. if (this._sceneDisposeObserver) {
  88885. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88886. }
  88887. if (this._originalPointerObserver) {
  88888. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88889. }
  88890. this.utilityLayerScene.dispose();
  88891. };
  88892. UtilityLayerRenderer.prototype._updateCamera = function () {
  88893. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88894. };
  88895. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88896. return UtilityLayerRenderer;
  88897. }());
  88898. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88899. })(BABYLON || (BABYLON = {}));
  88900. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88901. //# sourceMappingURL=babylon.behavior.js.map
  88902. var BABYLON;
  88903. (function (BABYLON) {
  88904. /**
  88905. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88906. */
  88907. var PointerDragBehavior = /** @class */ (function () {
  88908. /**
  88909. * Creates a pointer drag behavior that can be attached to a mesh
  88910. * @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)
  88911. */
  88912. function PointerDragBehavior(options) {
  88913. this.options = options;
  88914. /**
  88915. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88916. */
  88917. this.currentDraggingPointerID = -1;
  88918. /**
  88919. * If the behavior is currently in a dragging state
  88920. */
  88921. this.dragging = false;
  88922. /**
  88923. * 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)
  88924. */
  88925. this.dragDeltaRatio = 0.2;
  88926. /**
  88927. * If the drag plane orientation should be updated during the dragging (Default: true)
  88928. */
  88929. this.updateDragPlane = true;
  88930. // Debug mode will display drag planes to help visualize behavior
  88931. this._debugMode = false;
  88932. this._moving = false;
  88933. /**
  88934. * Fires each time the attached mesh is dragged with the pointer
  88935. * * delta between last drag position and current drag position in world space
  88936. * * dragDistance along the drag axis
  88937. * * dragPlaneNormal normal of the current drag plane used during the drag
  88938. * * dragPlanePoint in world space where the drag intersects the drag plane
  88939. */
  88940. this.onDragObservable = new BABYLON.Observable();
  88941. /**
  88942. * Fires each time a drag begins (eg. mouse down on mesh)
  88943. */
  88944. this.onDragStartObservable = new BABYLON.Observable();
  88945. /**
  88946. * Fires each time a drag ends (eg. mouse release after drag)
  88947. */
  88948. this.onDragEndObservable = new BABYLON.Observable();
  88949. /**
  88950. * If the attached mesh should be moved when dragged
  88951. */
  88952. this.moveAttached = true;
  88953. /**
  88954. * If the drag behavior will react to drag events (Default: true)
  88955. */
  88956. this.enabled = true;
  88957. /**
  88958. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88959. */
  88960. this.useObjectOrienationForDragging = true;
  88961. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88962. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88963. // Variables to avoid instantiation in the below method
  88964. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88965. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88966. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88967. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88968. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88969. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88970. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88971. var optionCount = 0;
  88972. if (options === undefined) {
  88973. options = {};
  88974. }
  88975. if (options.dragAxis) {
  88976. optionCount++;
  88977. }
  88978. if (options.dragPlaneNormal) {
  88979. optionCount++;
  88980. }
  88981. if (optionCount > 1) {
  88982. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88983. }
  88984. }
  88985. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88986. /**
  88987. * The name of the behavior
  88988. */
  88989. get: function () {
  88990. return "PointerDrag";
  88991. },
  88992. enumerable: true,
  88993. configurable: true
  88994. });
  88995. /**
  88996. * Initializes the behavior
  88997. */
  88998. PointerDragBehavior.prototype.init = function () { };
  88999. /**
  89000. * Attaches the drag behavior the passed in mesh
  89001. * @param ownerNode The mesh that will be dragged around once attached
  89002. */
  89003. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89004. var _this = this;
  89005. this._scene = ownerNode.getScene();
  89006. this._attachedNode = ownerNode;
  89007. // Initialize drag plane to not interfere with existing scene
  89008. if (!PointerDragBehavior._planeScene) {
  89009. if (this._debugMode) {
  89010. PointerDragBehavior._planeScene = this._scene;
  89011. }
  89012. else {
  89013. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89014. this._scene.getEngine().scenes.pop();
  89015. }
  89016. }
  89017. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89018. // State of the drag
  89019. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89020. var delta = new BABYLON.Vector3(0, 0, 0);
  89021. var dragLength = 0;
  89022. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89023. var pickPredicate = function (m) {
  89024. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89025. };
  89026. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89027. if (!_this.enabled) {
  89028. return;
  89029. }
  89030. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89031. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89032. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89033. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89034. if (pickedPoint) {
  89035. _this.dragging = true;
  89036. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89037. _this.lastDragPosition.copyFrom(pickedPoint);
  89038. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89039. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89040. }
  89041. }
  89042. }
  89043. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89044. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89045. _this.releaseDrag();
  89046. }
  89047. }
  89048. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89049. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89050. _this._moving = true;
  89051. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89052. if (pickedPoint) {
  89053. if (_this.updateDragPlane) {
  89054. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89055. }
  89056. // depending on the drag mode option drag accordingly
  89057. if (_this.options.dragAxis) {
  89058. // Convert local drag axis to world
  89059. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89060. // Project delta drag from the drag plane onto the drag axis
  89061. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89062. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89063. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89064. }
  89065. else {
  89066. dragLength = delta.length();
  89067. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89068. }
  89069. targetPosition.addInPlace(delta);
  89070. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89071. _this.lastDragPosition.copyFrom(pickedPoint);
  89072. }
  89073. }
  89074. }
  89075. });
  89076. this._scene.onBeforeRenderObservable.add(function () {
  89077. if (_this._moving && _this.moveAttached) {
  89078. // Slowly move mesh to avoid jitter
  89079. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89080. _this._tmpVector.scaleInPlace(0.2);
  89081. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89082. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89083. }
  89084. });
  89085. };
  89086. PointerDragBehavior.prototype.releaseDrag = function () {
  89087. this.dragging = false;
  89088. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89089. this.currentDraggingPointerID = -1;
  89090. this._moving = false;
  89091. };
  89092. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89093. var _this = this;
  89094. if (!ray) {
  89095. return null;
  89096. }
  89097. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89098. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89099. return pickResult.pickedPoint;
  89100. }
  89101. else {
  89102. return null;
  89103. }
  89104. };
  89105. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89106. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89107. this._pointA.copyFrom(dragPlanePosition);
  89108. if (this.options.dragAxis) {
  89109. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  89110. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89111. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89112. ray.origin.subtractToRef(this._pointA, this._pointC);
  89113. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89114. // Get perpendicular line from direction to camera and drag axis
  89115. this._pointB.subtractToRef(this._pointA, this._lineA);
  89116. this._pointC.subtractToRef(this._pointA, this._lineB);
  89117. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89118. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89119. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89120. this._lookAt.normalize();
  89121. this._dragPlane.position.copyFrom(this._pointA);
  89122. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89123. this._dragPlane.lookAt(this._lookAt);
  89124. }
  89125. else if (this.options.dragPlaneNormal) {
  89126. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  89127. this._dragPlane.position.copyFrom(this._pointA);
  89128. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89129. this._dragPlane.lookAt(this._lookAt);
  89130. }
  89131. else {
  89132. this._dragPlane.position.copyFrom(this._pointA);
  89133. this._dragPlane.lookAt(ray.origin);
  89134. }
  89135. this._dragPlane.computeWorldMatrix(true);
  89136. };
  89137. /**
  89138. * Detaches the behavior from the mesh
  89139. */
  89140. PointerDragBehavior.prototype.detach = function () {
  89141. if (this._pointerObserver) {
  89142. this._scene.onPointerObservable.remove(this._pointerObserver);
  89143. }
  89144. };
  89145. return PointerDragBehavior;
  89146. }());
  89147. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. /**
  89153. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89154. */
  89155. var MultiPointerScaleBehavior = /** @class */ (function () {
  89156. function MultiPointerScaleBehavior() {
  89157. this._startDistance = 0;
  89158. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89159. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89160. this._sceneRenderObserver = null;
  89161. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89162. this._dragBehaviorA.moveAttached = false;
  89163. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89164. this._dragBehaviorB.moveAttached = false;
  89165. }
  89166. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89167. /**
  89168. * The name of the behavior
  89169. */
  89170. get: function () {
  89171. return "MultiPointerScale";
  89172. },
  89173. enumerable: true,
  89174. configurable: true
  89175. });
  89176. /**
  89177. * Initializes the behavior
  89178. */
  89179. MultiPointerScaleBehavior.prototype.init = function () { };
  89180. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89181. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89182. };
  89183. /**
  89184. * Attaches the scale behavior the passed in mesh
  89185. * @param ownerNode The mesh that will be scaled around once attached
  89186. */
  89187. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89188. var _this = this;
  89189. this._ownerNode = ownerNode;
  89190. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89191. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89192. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89193. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89194. _this._dragBehaviorA.releaseDrag();
  89195. }
  89196. else {
  89197. _this._initialScale.copyFrom(ownerNode.scaling);
  89198. _this._startDistance = _this._getCurrentDistance();
  89199. }
  89200. }
  89201. });
  89202. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89203. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89204. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89205. _this._dragBehaviorB.releaseDrag();
  89206. }
  89207. else {
  89208. _this._initialScale.copyFrom(ownerNode.scaling);
  89209. _this._startDistance = _this._getCurrentDistance();
  89210. }
  89211. }
  89212. });
  89213. // Once both drag behaviors are active scale based on the distance between the two pointers
  89214. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89215. behavior.onDragObservable.add(function () {
  89216. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89217. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89218. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89219. }
  89220. });
  89221. });
  89222. ownerNode.addBehavior(this._dragBehaviorA);
  89223. ownerNode.addBehavior(this._dragBehaviorB);
  89224. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89225. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89226. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89227. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89228. if (change.length() > 0.01) {
  89229. ownerNode.scaling.addInPlace(change);
  89230. }
  89231. }
  89232. });
  89233. };
  89234. /**
  89235. * Detaches the behavior from the mesh
  89236. */
  89237. MultiPointerScaleBehavior.prototype.detach = function () {
  89238. var _this = this;
  89239. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89240. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89241. behavior.onDragStartObservable.clear();
  89242. behavior.onDragObservable.clear();
  89243. _this._ownerNode.removeBehavior(behavior);
  89244. });
  89245. };
  89246. return MultiPointerScaleBehavior;
  89247. }());
  89248. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89249. })(BABYLON || (BABYLON = {}));
  89250. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89251. var BABYLON;
  89252. (function (BABYLON) {
  89253. /**
  89254. * 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
  89255. */
  89256. var SixDofDragBehavior = /** @class */ (function () {
  89257. function SixDofDragBehavior() {
  89258. this._sceneRenderObserver = null;
  89259. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89260. this._moving = false;
  89261. this._startingOrientation = new BABYLON.Quaternion();
  89262. /**
  89263. * 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: 5)
  89264. */
  89265. this.zDragFactor = 5;
  89266. /**
  89267. * If the behavior is currently in a dragging state
  89268. */
  89269. this.dragging = false;
  89270. /**
  89271. * 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)
  89272. */
  89273. this.dragDeltaRatio = 0.2;
  89274. /**
  89275. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89276. */
  89277. this.currentDraggingPointerID = -1;
  89278. }
  89279. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89280. /**
  89281. * The name of the behavior
  89282. */
  89283. get: function () {
  89284. return "SixDofDrag";
  89285. },
  89286. enumerable: true,
  89287. configurable: true
  89288. });
  89289. /**
  89290. * Initializes the behavior
  89291. */
  89292. SixDofDragBehavior.prototype.init = function () { };
  89293. /**
  89294. * Attaches the scale behavior the passed in mesh
  89295. * @param ownerNode The mesh that will be scaled around once attached
  89296. */
  89297. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89298. var _this = this;
  89299. this._ownerNode = ownerNode;
  89300. this._scene = this._ownerNode.getScene();
  89301. if (!SixDofDragBehavior._virtualScene) {
  89302. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89303. this._scene.getEngine().scenes.pop();
  89304. }
  89305. var pickedMesh = null;
  89306. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89307. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89308. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89309. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89310. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89311. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89312. var pickPredicate = function (m) {
  89313. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89314. };
  89315. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89316. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89317. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89318. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89319. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89320. // Set position and orientation of the controller
  89321. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89322. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89323. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89324. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89325. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89326. if (!pickedMesh.rotationQuaternion) {
  89327. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89328. }
  89329. var oldParent = pickedMesh.parent;
  89330. pickedMesh.setParent(null);
  89331. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89332. pickedMesh.setParent(oldParent);
  89333. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89334. // Update state
  89335. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89336. _this.dragging = true;
  89337. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89338. }
  89339. }
  89340. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89341. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89342. _this.dragging = false;
  89343. _this._moving = false;
  89344. _this.currentDraggingPointerID = -1;
  89345. pickedMesh = null;
  89346. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89347. }
  89348. }
  89349. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89350. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89351. // Calculate controller drag distance in controller space
  89352. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89353. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89354. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89355. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89356. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89357. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89358. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89359. if (_this._virtualDragMesh.position.z < 0) {
  89360. _this._virtualDragMesh.position.z = 0;
  89361. }
  89362. // Update the controller position
  89363. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89364. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89365. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89366. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89367. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89368. if (pickedMesh.parent) {
  89369. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89370. }
  89371. if (!_this._moving) {
  89372. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89373. }
  89374. _this._moving = true;
  89375. }
  89376. }
  89377. });
  89378. var tmpQuaternion = new BABYLON.Quaternion();
  89379. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89380. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89381. if (_this.dragging && _this._moving && pickedMesh) {
  89382. // Slowly move mesh to avoid jitter
  89383. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89384. // Get change in rotation
  89385. tmpQuaternion.copyFrom(_this._startingOrientation);
  89386. tmpQuaternion.x = -tmpQuaternion.x;
  89387. tmpQuaternion.y = -tmpQuaternion.y;
  89388. tmpQuaternion.z = -tmpQuaternion.z;
  89389. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89390. // Convert change in rotation to only y axis rotation
  89391. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89392. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89393. // Slowly move mesh to avoid jitter
  89394. var oldParent = pickedMesh.parent;
  89395. pickedMesh.setParent(null);
  89396. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89397. pickedMesh.setParent(oldParent);
  89398. }
  89399. });
  89400. };
  89401. /**
  89402. * Detaches the behavior from the mesh
  89403. */
  89404. SixDofDragBehavior.prototype.detach = function () {
  89405. this._scene.onPointerObservable.remove(this._pointerObserver);
  89406. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89407. this._virtualOriginMesh.dispose();
  89408. this._virtualDragMesh.dispose();
  89409. };
  89410. return SixDofDragBehavior;
  89411. }());
  89412. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89413. })(BABYLON || (BABYLON = {}));
  89414. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89415. var BABYLON;
  89416. (function (BABYLON) {
  89417. /**
  89418. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89419. */
  89420. var Gizmo = /** @class */ (function () {
  89421. /**
  89422. * Creates a gizmo
  89423. * @param gizmoLayer The utility layer the gizmo will be added to
  89424. */
  89425. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89426. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89427. var _this = this;
  89428. this.gizmoLayer = gizmoLayer;
  89429. this._scaleFactor = 3;
  89430. /**
  89431. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89432. */
  89433. this.updateGizmoRotationToMatchAttachedMesh = true;
  89434. /**
  89435. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89436. */
  89437. this.updateGizmoPositionToMatchAttachedMesh = true;
  89438. /**
  89439. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89440. */
  89441. this._updateScale = true;
  89442. this._interactionsEnabled = true;
  89443. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89444. var tempVector = new BABYLON.Vector3();
  89445. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89446. if (_this.attachedMesh) {
  89447. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89448. if (!_this._rootMesh.rotationQuaternion) {
  89449. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  89450. }
  89451. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  89452. }
  89453. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89454. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89455. }
  89456. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89457. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89458. var dist = tempVector.length() / _this._scaleFactor;
  89459. _this._rootMesh.scaling.set(dist, dist, dist);
  89460. }
  89461. }
  89462. });
  89463. this.attachedMesh = null;
  89464. }
  89465. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89466. /**
  89467. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89468. * * When set, interactions will be enabled
  89469. */
  89470. get: function () {
  89471. return this._attachedMesh;
  89472. },
  89473. set: function (value) {
  89474. this._attachedMesh = value;
  89475. this._rootMesh.setEnabled(value ? true : false);
  89476. this._attachedMeshChanged(value);
  89477. },
  89478. enumerable: true,
  89479. configurable: true
  89480. });
  89481. Gizmo.prototype._attachedMeshChanged = function (value) {
  89482. };
  89483. /**
  89484. * Disposes of the gizmo
  89485. */
  89486. Gizmo.prototype.dispose = function () {
  89487. this._rootMesh.dispose();
  89488. if (this._beforeRenderObserver) {
  89489. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89490. }
  89491. };
  89492. return Gizmo;
  89493. }());
  89494. BABYLON.Gizmo = Gizmo;
  89495. })(BABYLON || (BABYLON = {}));
  89496. //# sourceMappingURL=babylon.gizmo.js.map
  89497. var BABYLON;
  89498. (function (BABYLON) {
  89499. /**
  89500. * Single axis drag gizmo
  89501. */
  89502. var AxisDragGizmo = /** @class */ (function (_super) {
  89503. __extends(AxisDragGizmo, _super);
  89504. /**
  89505. * Creates an AxisDragGizmo
  89506. * @param gizmoLayer The utility layer the gizmo will be added to
  89507. * @param dragAxis The axis which the gizmo will be able to drag on
  89508. * @param color The color of the gizmo
  89509. */
  89510. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89511. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89512. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89513. var _this = _super.call(this, gizmoLayer) || this;
  89514. _this._pointerObserver = null;
  89515. /**
  89516. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89517. */
  89518. _this.snapDistance = 0;
  89519. /**
  89520. * Event that fires each time the gizmo snaps to a new location.
  89521. * * snapDistance is the the change in distance
  89522. */
  89523. _this.onSnapObservable = new BABYLON.Observable();
  89524. // Create Material
  89525. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89526. coloredMaterial.disableLighting = true;
  89527. coloredMaterial.emissiveColor = color;
  89528. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89529. hoverMaterial.disableLighting = true;
  89530. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89531. // Build mesh on root node
  89532. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89533. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89534. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89535. arrow.addChild(arrowMesh);
  89536. arrow.addChild(arrowTail);
  89537. // Position arrow pointing in its drag axis
  89538. arrowMesh.scaling.scaleInPlace(0.05);
  89539. arrowMesh.material = coloredMaterial;
  89540. arrowMesh.rotation.x = Math.PI / 2;
  89541. arrowMesh.position.z += 0.3;
  89542. arrowTail.rotation.x = Math.PI / 2;
  89543. arrowTail.material = coloredMaterial;
  89544. arrowTail.position.z += 0.15;
  89545. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89546. _this._rootMesh.addChild(arrow);
  89547. var currentSnapDragDistance = 0;
  89548. var tmpVector = new BABYLON.Vector3();
  89549. var tmpSnapEvent = { snapDistance: 0 };
  89550. // Add drag behavior to handle events when the gizmo is dragged
  89551. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89552. _this.dragBehavior.moveAttached = false;
  89553. _this._rootMesh.addBehavior(_this.dragBehavior);
  89554. _this.dragBehavior.onDragObservable.add(function (event) {
  89555. if (_this.attachedMesh) {
  89556. // Snapping logic
  89557. if (_this.snapDistance == 0) {
  89558. _this.attachedMesh.position.addInPlace(event.delta);
  89559. }
  89560. else {
  89561. currentSnapDragDistance += event.dragDistance;
  89562. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89563. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89564. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89565. event.delta.normalizeToRef(tmpVector);
  89566. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89567. _this.attachedMesh.position.addInPlace(tmpVector);
  89568. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89569. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89570. }
  89571. }
  89572. }
  89573. });
  89574. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89575. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89576. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89577. m.material = hoverMaterial;
  89578. });
  89579. }
  89580. else {
  89581. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89582. m.material = coloredMaterial;
  89583. });
  89584. }
  89585. });
  89586. return _this;
  89587. }
  89588. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89589. if (this.dragBehavior) {
  89590. this.dragBehavior.enabled = value ? true : false;
  89591. }
  89592. };
  89593. /**
  89594. * Disposes of the gizmo
  89595. */
  89596. AxisDragGizmo.prototype.dispose = function () {
  89597. this.onSnapObservable.clear();
  89598. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89599. this.dragBehavior.detach();
  89600. _super.prototype.dispose.call(this);
  89601. };
  89602. return AxisDragGizmo;
  89603. }(BABYLON.Gizmo));
  89604. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89605. })(BABYLON || (BABYLON = {}));
  89606. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89607. var BABYLON;
  89608. (function (BABYLON) {
  89609. /**
  89610. * Single axis scale gizmo
  89611. */
  89612. var AxisScaleGizmo = /** @class */ (function (_super) {
  89613. __extends(AxisScaleGizmo, _super);
  89614. /**
  89615. * Creates an AxisScaleGizmo
  89616. * @param gizmoLayer The utility layer the gizmo will be added to
  89617. * @param dragAxis The axis which the gizmo will be able to scale on
  89618. * @param color The color of the gizmo
  89619. */
  89620. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89621. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89622. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89623. var _this = _super.call(this, gizmoLayer) || this;
  89624. _this._pointerObserver = null;
  89625. /**
  89626. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89627. */
  89628. _this.snapDistance = 0;
  89629. /**
  89630. * Event that fires each time the gizmo snaps to a new location.
  89631. * * snapDistance is the the change in distance
  89632. */
  89633. _this.onSnapObservable = new BABYLON.Observable();
  89634. // Create Material
  89635. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89636. coloredMaterial.disableLighting = true;
  89637. coloredMaterial.emissiveColor = color;
  89638. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89639. hoverMaterial.disableLighting = true;
  89640. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89641. // Build mesh on root node
  89642. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89643. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89644. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89645. arrow.addChild(arrowMesh);
  89646. arrow.addChild(arrowTail);
  89647. // Position arrow pointing in its drag axis
  89648. arrowMesh.scaling.scaleInPlace(0.1);
  89649. arrowMesh.material = coloredMaterial;
  89650. arrowMesh.rotation.x = Math.PI / 2;
  89651. arrowMesh.position.z += 0.3;
  89652. arrowTail.rotation.x = Math.PI / 2;
  89653. arrowTail.material = coloredMaterial;
  89654. arrowTail.position.z += 0.15;
  89655. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89656. _this._rootMesh.addChild(arrow);
  89657. // Add drag behavior to handle events when the gizmo is dragged
  89658. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89659. _this.dragBehavior.moveAttached = false;
  89660. _this._rootMesh.addBehavior(_this.dragBehavior);
  89661. var currentSnapDragDistance = 0;
  89662. var tmpVector = new BABYLON.Vector3();
  89663. var tmpSnapEvent = { snapDistance: 0 };
  89664. _this.dragBehavior.onDragObservable.add(function (event) {
  89665. if (_this.attachedMesh) {
  89666. // Snapping logic
  89667. var snapped = false;
  89668. var dragSteps = 0;
  89669. if (_this.snapDistance == 0) {
  89670. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89671. }
  89672. else {
  89673. currentSnapDragDistance += event.dragDistance;
  89674. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89675. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89676. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89677. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89678. snapped = true;
  89679. }
  89680. else {
  89681. tmpVector.scaleInPlace(0);
  89682. }
  89683. }
  89684. var invertCount = 0;
  89685. if (_this.attachedMesh.scaling["x"] < 0) {
  89686. invertCount++;
  89687. }
  89688. if (_this.attachedMesh.scaling["y"] < 0) {
  89689. invertCount++;
  89690. }
  89691. if (_this.attachedMesh.scaling["z"] < 0) {
  89692. invertCount++;
  89693. }
  89694. if (invertCount % 2 == 0) {
  89695. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89696. }
  89697. else {
  89698. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89699. }
  89700. if (snapped) {
  89701. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89702. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89703. }
  89704. }
  89705. });
  89706. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89707. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89708. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89709. m.material = hoverMaterial;
  89710. });
  89711. }
  89712. else {
  89713. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89714. m.material = coloredMaterial;
  89715. });
  89716. }
  89717. });
  89718. return _this;
  89719. }
  89720. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89721. if (this.dragBehavior) {
  89722. this.dragBehavior.enabled = value ? true : false;
  89723. }
  89724. };
  89725. /**
  89726. * Disposes of the gizmo
  89727. */
  89728. AxisScaleGizmo.prototype.dispose = function () {
  89729. this.onSnapObservable.clear();
  89730. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89731. this.dragBehavior.detach();
  89732. _super.prototype.dispose.call(this);
  89733. };
  89734. return AxisScaleGizmo;
  89735. }(BABYLON.Gizmo));
  89736. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89737. })(BABYLON || (BABYLON = {}));
  89738. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89739. var BABYLON;
  89740. (function (BABYLON) {
  89741. /**
  89742. * Single plane rotation gizmo
  89743. */
  89744. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89745. __extends(PlaneRotationGizmo, _super);
  89746. /**
  89747. * Creates a PlaneRotationGizmo
  89748. * @param gizmoLayer The utility layer the gizmo will be added to
  89749. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89750. * @param color The color of the gizmo
  89751. */
  89752. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89753. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89754. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89755. var _this = _super.call(this, gizmoLayer) || this;
  89756. _this._pointerObserver = null;
  89757. /**
  89758. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89759. */
  89760. _this.snapDistance = 0;
  89761. /**
  89762. * Event that fires each time the gizmo snaps to a new location.
  89763. * * snapDistance is the the change in distance
  89764. */
  89765. _this.onSnapObservable = new BABYLON.Observable();
  89766. // Create Material
  89767. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89768. coloredMaterial.disableLighting = true;
  89769. coloredMaterial.emissiveColor = color;
  89770. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89771. hoverMaterial.disableLighting = true;
  89772. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89773. // Build mesh on root node
  89774. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89775. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89776. // Position arrow pointing in its drag axis
  89777. rotationMesh.scaling.scaleInPlace(0.1);
  89778. rotationMesh.material = coloredMaterial;
  89779. rotationMesh.rotation.x = Math.PI / 2;
  89780. parentMesh.addChild(rotationMesh);
  89781. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89782. _this._rootMesh.addChild(parentMesh);
  89783. // Add drag behavior to handle events when the gizmo is dragged
  89784. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89785. _this.dragBehavior.moveAttached = false;
  89786. _this._rootMesh.addBehavior(_this.dragBehavior);
  89787. var lastDragPosition = null;
  89788. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89789. if (_this.attachedMesh) {
  89790. lastDragPosition = e.dragPlanePoint;
  89791. }
  89792. });
  89793. var rotationMatrix = new BABYLON.Matrix();
  89794. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89795. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89796. var tmpSnapEvent = { snapDistance: 0 };
  89797. var currentSnapDragDistance = 0;
  89798. _this.dragBehavior.onDragObservable.add(function (event) {
  89799. if (_this.attachedMesh && lastDragPosition) {
  89800. if (!_this.attachedMesh.rotationQuaternion) {
  89801. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89802. }
  89803. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89804. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89805. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89806. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89807. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89808. var angle = Math.atan2(cross.length(), dot);
  89809. planeNormalTowardsCamera.copyFrom(planeNormal);
  89810. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89811. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89812. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89813. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89814. }
  89815. // Flip up vector depending on which side the camera is on
  89816. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89817. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89818. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89819. planeNormalTowardsCamera.scaleInPlace(-1);
  89820. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89821. }
  89822. }
  89823. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89824. if (halfCircleSide)
  89825. angle = -angle;
  89826. // Snapping logic
  89827. var snapped = false;
  89828. if (_this.snapDistance != 0) {
  89829. currentSnapDragDistance += angle;
  89830. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89831. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89832. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89833. angle = _this.snapDistance * dragSteps;
  89834. snapped = true;
  89835. }
  89836. else {
  89837. angle = 0;
  89838. }
  89839. }
  89840. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89841. var quaternionCoefficient = Math.sin(angle / 2);
  89842. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89843. // Rotate selected mesh quaternion over fixed axis
  89844. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89845. lastDragPosition = event.dragPlanePoint;
  89846. if (snapped) {
  89847. tmpSnapEvent.snapDistance = angle;
  89848. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89849. }
  89850. }
  89851. });
  89852. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89853. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89854. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89855. m.material = hoverMaterial;
  89856. });
  89857. }
  89858. else {
  89859. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89860. m.material = coloredMaterial;
  89861. });
  89862. }
  89863. });
  89864. return _this;
  89865. }
  89866. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89867. if (this.dragBehavior) {
  89868. this.dragBehavior.enabled = value ? true : false;
  89869. }
  89870. };
  89871. /**
  89872. * Disposes of the gizmo
  89873. */
  89874. PlaneRotationGizmo.prototype.dispose = function () {
  89875. this.onSnapObservable.clear();
  89876. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89877. this.dragBehavior.detach();
  89878. _super.prototype.dispose.call(this);
  89879. };
  89880. return PlaneRotationGizmo;
  89881. }(BABYLON.Gizmo));
  89882. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89883. })(BABYLON || (BABYLON = {}));
  89884. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89885. var BABYLON;
  89886. (function (BABYLON) {
  89887. /**
  89888. * Gizmo that enables dragging a mesh along 3 axis
  89889. */
  89890. var PositionGizmo = /** @class */ (function (_super) {
  89891. __extends(PositionGizmo, _super);
  89892. /**
  89893. * Creates a PositionGizmo
  89894. * @param gizmoLayer The utility layer the gizmo will be added to
  89895. */
  89896. function PositionGizmo(gizmoLayer) {
  89897. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89898. var _this = _super.call(this, gizmoLayer) || this;
  89899. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89900. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89901. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89902. _this.attachedMesh = null;
  89903. return _this;
  89904. }
  89905. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89906. set: function (mesh) {
  89907. if (this.xGizmo) {
  89908. this.xGizmo.attachedMesh = mesh;
  89909. this.yGizmo.attachedMesh = mesh;
  89910. this.zGizmo.attachedMesh = mesh;
  89911. }
  89912. },
  89913. enumerable: true,
  89914. configurable: true
  89915. });
  89916. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89917. get: function () {
  89918. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89919. },
  89920. set: function (value) {
  89921. if (this.xGizmo) {
  89922. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89923. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89924. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89925. }
  89926. },
  89927. enumerable: true,
  89928. configurable: true
  89929. });
  89930. /**
  89931. * Disposes of the gizmo
  89932. */
  89933. PositionGizmo.prototype.dispose = function () {
  89934. this.xGizmo.dispose();
  89935. this.yGizmo.dispose();
  89936. this.zGizmo.dispose();
  89937. };
  89938. return PositionGizmo;
  89939. }(BABYLON.Gizmo));
  89940. BABYLON.PositionGizmo = PositionGizmo;
  89941. })(BABYLON || (BABYLON = {}));
  89942. //# sourceMappingURL=babylon.positionGizmo.js.map
  89943. var BABYLON;
  89944. (function (BABYLON) {
  89945. /**
  89946. * Gizmo that enables rotating a mesh along 3 axis
  89947. */
  89948. var RotationGizmo = /** @class */ (function (_super) {
  89949. __extends(RotationGizmo, _super);
  89950. /**
  89951. * Creates a RotationGizmo
  89952. * @param gizmoLayer The utility layer the gizmo will be added to
  89953. */
  89954. function RotationGizmo(gizmoLayer) {
  89955. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89956. var _this = _super.call(this, gizmoLayer) || this;
  89957. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89958. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89959. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89960. _this.attachedMesh = null;
  89961. return _this;
  89962. }
  89963. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89964. set: function (mesh) {
  89965. if (this.xGizmo) {
  89966. this.xGizmo.attachedMesh = mesh;
  89967. this.yGizmo.attachedMesh = mesh;
  89968. this.zGizmo.attachedMesh = mesh;
  89969. }
  89970. },
  89971. enumerable: true,
  89972. configurable: true
  89973. });
  89974. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89975. get: function () {
  89976. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89977. },
  89978. set: function (value) {
  89979. if (this.xGizmo) {
  89980. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89981. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89982. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89983. }
  89984. },
  89985. enumerable: true,
  89986. configurable: true
  89987. });
  89988. /**
  89989. * Disposes of the gizmo
  89990. */
  89991. RotationGizmo.prototype.dispose = function () {
  89992. this.xGizmo.dispose();
  89993. this.yGizmo.dispose();
  89994. this.zGizmo.dispose();
  89995. };
  89996. return RotationGizmo;
  89997. }(BABYLON.Gizmo));
  89998. BABYLON.RotationGizmo = RotationGizmo;
  89999. })(BABYLON || (BABYLON = {}));
  90000. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90001. var BABYLON;
  90002. (function (BABYLON) {
  90003. /**
  90004. * Gizmo that enables scaling a mesh along 3 axis
  90005. */
  90006. var ScaleGizmo = /** @class */ (function (_super) {
  90007. __extends(ScaleGizmo, _super);
  90008. /**
  90009. * Creates a ScaleGizmo
  90010. * @param gizmoLayer The utility layer the gizmo will be added to
  90011. */
  90012. function ScaleGizmo(gizmoLayer) {
  90013. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90014. var _this = _super.call(this, gizmoLayer) || this;
  90015. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90016. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90017. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90018. _this.attachedMesh = null;
  90019. return _this;
  90020. }
  90021. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90022. set: function (mesh) {
  90023. if (this.xGizmo) {
  90024. this.xGizmo.attachedMesh = mesh;
  90025. this.yGizmo.attachedMesh = mesh;
  90026. this.zGizmo.attachedMesh = mesh;
  90027. }
  90028. },
  90029. enumerable: true,
  90030. configurable: true
  90031. });
  90032. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90033. get: function () {
  90034. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90035. },
  90036. set: function (value) {
  90037. if (this.xGizmo) {
  90038. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90039. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90040. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90041. }
  90042. },
  90043. enumerable: true,
  90044. configurable: true
  90045. });
  90046. /**
  90047. * Disposes of the gizmo
  90048. */
  90049. ScaleGizmo.prototype.dispose = function () {
  90050. this.xGizmo.dispose();
  90051. this.yGizmo.dispose();
  90052. this.zGizmo.dispose();
  90053. };
  90054. return ScaleGizmo;
  90055. }(BABYLON.Gizmo));
  90056. BABYLON.ScaleGizmo = ScaleGizmo;
  90057. })(BABYLON || (BABYLON = {}));
  90058. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90059. var BABYLON;
  90060. (function (BABYLON) {
  90061. /**
  90062. * Bounding box gizmo
  90063. */
  90064. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90065. __extends(BoundingBoxGizmo, _super);
  90066. /**
  90067. * Creates an BoundingBoxGizmo
  90068. * @param gizmoLayer The utility layer the gizmo will be added to
  90069. * @param color The color of the gizmo
  90070. */
  90071. function BoundingBoxGizmo(color, gizmoLayer) {
  90072. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90073. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90074. var _this = _super.call(this, gizmoLayer) || this;
  90075. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90076. _this._renderObserver = null;
  90077. _this._pointerObserver = null;
  90078. _this._scaleDragSpeed = 0.2;
  90079. _this._tmpQuaternion = new BABYLON.Quaternion();
  90080. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90081. /**
  90082. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90083. */
  90084. _this.rotationSphereSize = 0.1;
  90085. /**
  90086. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90087. */
  90088. _this.scaleBoxSize = 0.1;
  90089. /**
  90090. * 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)
  90091. */
  90092. _this.fixedDragMeshScreenSize = false;
  90093. /**
  90094. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90095. */
  90096. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90097. /**
  90098. * Fired when a rotation sphere or scale box is dragged
  90099. */
  90100. _this.onDragStartObservable = new BABYLON.Observable();
  90101. /**
  90102. * Fired when a rotation sphere or scale box drag is started
  90103. */
  90104. _this.onDragObservable = new BABYLON.Observable();
  90105. /**
  90106. * Fired when a rotation sphere or scale box drag is needed
  90107. */
  90108. _this.onDragEndObservable = new BABYLON.Observable();
  90109. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90110. _this._updateScale = false;
  90111. // Create Materials
  90112. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90113. coloredMaterial.disableLighting = true;
  90114. coloredMaterial.emissiveColor = color;
  90115. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90116. hoverColoredMaterial.disableLighting = true;
  90117. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90118. // Build bounding box out of lines
  90119. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90120. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90121. var lines = [];
  90122. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90123. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90124. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90125. 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));
  90126. 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));
  90127. 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));
  90128. 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));
  90129. 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));
  90130. 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));
  90131. 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));
  90132. 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));
  90133. 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));
  90134. lines.forEach(function (l) {
  90135. l.color = color;
  90136. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90137. l.isPickable = false;
  90138. _this._lineBoundingBox.addChild(l);
  90139. });
  90140. _this._rootMesh.addChild(_this._lineBoundingBox);
  90141. // Create rotation spheres
  90142. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90143. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90144. var _loop_1 = function (i_1) {
  90145. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90146. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90147. sphere.material = coloredMaterial;
  90148. // Drag behavior
  90149. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90150. _dragBehavior.moveAttached = false;
  90151. _dragBehavior.updateDragPlane = false;
  90152. sphere.addBehavior(_dragBehavior);
  90153. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90154. var totalTurnAmountOfDrag = 0;
  90155. _dragBehavior.onDragStartObservable.add(function (event) {
  90156. startingTurnDirection.copyFrom(sphere.forward);
  90157. totalTurnAmountOfDrag = 0;
  90158. });
  90159. _dragBehavior.onDragObservable.add(function (event) {
  90160. _this.onDragObservable.notifyObservers({});
  90161. if (_this.attachedMesh) {
  90162. var worldDragDirection = startingTurnDirection;
  90163. // Project the world right on to the drag plane
  90164. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90165. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90166. // project drag delta on to the resulting drag axis and rotate based on that
  90167. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90168. // Rotate based on axis
  90169. if (!_this.attachedMesh.rotationQuaternion) {
  90170. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90171. }
  90172. // Do not allow the object to turn more than a full circle
  90173. totalTurnAmountOfDrag += projectDist;
  90174. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90175. if (i_1 >= 8) {
  90176. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90177. }
  90178. else if (i_1 >= 4) {
  90179. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90180. }
  90181. else {
  90182. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90183. }
  90184. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  90185. }
  90186. }
  90187. });
  90188. // Selection/deselection
  90189. _dragBehavior.onDragStartObservable.add(function () {
  90190. _this.onDragStartObservable.notifyObservers({});
  90191. _this._selectNode(sphere);
  90192. });
  90193. _dragBehavior.onDragEndObservable.add(function () {
  90194. _this.onDragEndObservable.notifyObservers({});
  90195. _this._selectNode(null);
  90196. });
  90197. this_1._rotateSpheresParent.addChild(sphere);
  90198. };
  90199. var this_1 = this, _dragBehavior;
  90200. for (var i_1 = 0; i_1 < 12; i_1++) {
  90201. _loop_1(i_1);
  90202. }
  90203. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90204. // Create scale cubes
  90205. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90206. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90207. for (var i = 0; i < 2; i++) {
  90208. for (var j = 0; j < 2; j++) {
  90209. var _loop_2 = function () {
  90210. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90211. box.material = coloredMaterial;
  90212. // Dragging logic
  90213. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90214. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90215. _dragBehavior.moveAttached = false;
  90216. box.addBehavior(_dragBehavior);
  90217. _dragBehavior.onDragObservable.add(function (event) {
  90218. _this.onDragObservable.notifyObservers({});
  90219. if (_this.attachedMesh) {
  90220. // Current boudning box dimensions
  90221. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90222. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90223. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90224. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90225. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90226. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90227. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90228. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90229. // Update scale and position
  90230. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90231. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90232. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90233. }
  90234. });
  90235. // Selection/deselection
  90236. _dragBehavior.onDragStartObservable.add(function () {
  90237. _this.onDragStartObservable.notifyObservers({});
  90238. _this._selectNode(box);
  90239. });
  90240. _dragBehavior.onDragEndObservable.add(function () {
  90241. _this.onDragEndObservable.notifyObservers({});
  90242. _this._selectNode(null);
  90243. });
  90244. this_2._scaleBoxesParent.addChild(box);
  90245. };
  90246. var this_2 = this, _dragBehavior;
  90247. for (var k = 0; k < 2; k++) {
  90248. _loop_2();
  90249. }
  90250. }
  90251. }
  90252. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90253. // Hover color change
  90254. var pointerIds = new Array();
  90255. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90256. if (!pointerIds[pointerInfo.event.pointerId]) {
  90257. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90258. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90259. pointerIds[pointerInfo.event.pointerId] = mesh;
  90260. mesh.material = hoverColoredMaterial;
  90261. }
  90262. });
  90263. }
  90264. else {
  90265. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90266. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90267. delete pointerIds[pointerInfo.event.pointerId];
  90268. }
  90269. }
  90270. });
  90271. // Update bounding box positions
  90272. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90273. _this._updateBoundingBox();
  90274. });
  90275. _this._updateBoundingBox();
  90276. return _this;
  90277. }
  90278. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90279. this._rotateSpheresParent.getChildMeshes()
  90280. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90281. m.isVisible = (!selectedMesh || m == selectedMesh);
  90282. });
  90283. };
  90284. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90285. if (this.attachedMesh) {
  90286. // Update bounding dimensions/positions
  90287. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90288. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90289. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90290. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90291. }
  90292. // Update rotation sphere locations
  90293. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90294. for (var i = 0; i < 3; i++) {
  90295. for (var j = 0; j < 2; j++) {
  90296. for (var k = 0; k < 2; k++) {
  90297. var index = ((i * 4) + (j * 2)) + k;
  90298. if (i == 0) {
  90299. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90300. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90301. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90302. }
  90303. if (i == 1) {
  90304. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90305. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90306. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90307. }
  90308. if (i == 2) {
  90309. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90310. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90311. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90312. }
  90313. if (this.fixedDragMeshScreenSize) {
  90314. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90315. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90316. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90317. }
  90318. else {
  90319. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90320. }
  90321. }
  90322. }
  90323. }
  90324. // Update scale box locations
  90325. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90326. for (var i = 0; i < 2; i++) {
  90327. for (var j = 0; j < 2; j++) {
  90328. for (var k = 0; k < 2; k++) {
  90329. var index = ((i * 4) + (j * 2)) + k;
  90330. if (scaleBoxes[index]) {
  90331. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90332. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90333. if (this.fixedDragMeshScreenSize) {
  90334. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90335. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90336. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90337. }
  90338. else {
  90339. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90340. }
  90341. }
  90342. }
  90343. }
  90344. }
  90345. };
  90346. /**
  90347. * Enables rotation on the specified axis and disables rotation on the others
  90348. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90349. */
  90350. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90351. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90352. if (i < 4) {
  90353. m.setEnabled(axis.indexOf("x") != -1);
  90354. }
  90355. else if (i < 8) {
  90356. m.setEnabled(axis.indexOf("y") != -1);
  90357. }
  90358. else {
  90359. m.setEnabled(axis.indexOf("z") != -1);
  90360. }
  90361. });
  90362. };
  90363. /**
  90364. * Disposes of the gizmo
  90365. */
  90366. BoundingBoxGizmo.prototype.dispose = function () {
  90367. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90368. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90369. this._lineBoundingBox.dispose();
  90370. this._rotateSpheresParent.dispose();
  90371. this._scaleBoxesParent.dispose();
  90372. _super.prototype.dispose.call(this);
  90373. };
  90374. return BoundingBoxGizmo;
  90375. }(BABYLON.Gizmo));
  90376. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90377. })(BABYLON || (BABYLON = {}));
  90378. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90379. var BABYLON;
  90380. (function (BABYLON) {
  90381. /**
  90382. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90383. */
  90384. var GizmoManager = /** @class */ (function () {
  90385. /**
  90386. * Instatiates a gizmo manager
  90387. * @param scene the scene to overlay the gizmos on top of
  90388. * @param options If only a single gizmo should exist at one time
  90389. */
  90390. function GizmoManager(scene, options) {
  90391. var _this = this;
  90392. this.scene = scene;
  90393. // Set of gizmos that are currently in the scene for each mesh
  90394. this._gizmoSet = {};
  90395. this._pointerObserver = null;
  90396. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90397. // Options parsing
  90398. if (!options) {
  90399. options = {};
  90400. }
  90401. if (options.singleGizmo === undefined) {
  90402. options.singleGizmo = true;
  90403. }
  90404. // Instatiate/dispose gizmos based on pointer actions
  90405. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90406. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90407. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90408. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90409. if (options.singleGizmo) {
  90410. _this._clearGizmos();
  90411. }
  90412. // Enable gizmo when mesh is selected
  90413. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90414. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90415. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90416. }
  90417. else {
  90418. if (!options.singleGizmo) {
  90419. // Disable gizmo when clicked again
  90420. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90421. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90422. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90423. }
  90424. }
  90425. }
  90426. else {
  90427. if (options.singleGizmo) {
  90428. // Disable gizmo when clicked away
  90429. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90430. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90431. if (gizmoPick && !gizmoPick.hit) {
  90432. _this._clearGizmos();
  90433. }
  90434. }
  90435. }
  90436. }
  90437. }
  90438. });
  90439. }
  90440. /**
  90441. * Disposes of the gizmo manager
  90442. */
  90443. GizmoManager.prototype.dispose = function () {
  90444. this.scene.onPointerObservable.remove(this._pointerObserver);
  90445. this._clearGizmos();
  90446. this._gizmoLayer.dispose();
  90447. };
  90448. GizmoManager.prototype._clearGizmos = function () {
  90449. for (var key in this._gizmoSet) {
  90450. if (this._gizmoSet.hasOwnProperty(key)) {
  90451. this._gizmoSet[key].positionGizmo.dispose();
  90452. this._gizmoSet[key].rotationGizmo.dispose();
  90453. delete this._gizmoSet[key];
  90454. }
  90455. }
  90456. };
  90457. return GizmoManager;
  90458. }());
  90459. BABYLON.GizmoManager = GizmoManager;
  90460. })(BABYLON || (BABYLON = {}));
  90461. //# sourceMappingURL=babylon.gizmoManager.js.map
  90462. var BABYLON;
  90463. (function (BABYLON) {
  90464. /**
  90465. * Defines a target to use with MorphTargetManager
  90466. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90467. */
  90468. var MorphTarget = /** @class */ (function () {
  90469. /**
  90470. * Creates a new MorphTarget
  90471. * @param name defines the name of the target
  90472. * @param influence defines the influence to use
  90473. */
  90474. function MorphTarget(
  90475. /** defines the name of the target */
  90476. name, influence, scene) {
  90477. if (influence === void 0) { influence = 0; }
  90478. if (scene === void 0) { scene = null; }
  90479. this.name = name;
  90480. /**
  90481. * Gets or sets the list of animations
  90482. */
  90483. this.animations = new Array();
  90484. this._positions = null;
  90485. this._normals = null;
  90486. this._tangents = null;
  90487. /**
  90488. * Observable raised when the influence changes
  90489. */
  90490. this.onInfluenceChanged = new BABYLON.Observable();
  90491. this._animationPropertiesOverride = null;
  90492. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90493. this.influence = influence;
  90494. }
  90495. Object.defineProperty(MorphTarget.prototype, "influence", {
  90496. /**
  90497. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90498. */
  90499. get: function () {
  90500. return this._influence;
  90501. },
  90502. set: function (influence) {
  90503. if (this._influence === influence) {
  90504. return;
  90505. }
  90506. var previous = this._influence;
  90507. this._influence = influence;
  90508. if (this.onInfluenceChanged.hasObservers) {
  90509. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90510. }
  90511. },
  90512. enumerable: true,
  90513. configurable: true
  90514. });
  90515. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90516. /**
  90517. * Gets or sets the animation properties override
  90518. */
  90519. get: function () {
  90520. if (!this._animationPropertiesOverride && this._scene) {
  90521. return this._scene.animationPropertiesOverride;
  90522. }
  90523. return this._animationPropertiesOverride;
  90524. },
  90525. set: function (value) {
  90526. this._animationPropertiesOverride = value;
  90527. },
  90528. enumerable: true,
  90529. configurable: true
  90530. });
  90531. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90532. /**
  90533. * Gets a boolean defining if the target contains position data
  90534. */
  90535. get: function () {
  90536. return !!this._positions;
  90537. },
  90538. enumerable: true,
  90539. configurable: true
  90540. });
  90541. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90542. /**
  90543. * Gets a boolean defining if the target contains normal data
  90544. */
  90545. get: function () {
  90546. return !!this._normals;
  90547. },
  90548. enumerable: true,
  90549. configurable: true
  90550. });
  90551. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90552. /**
  90553. * Gets a boolean defining if the target contains tangent data
  90554. */
  90555. get: function () {
  90556. return !!this._tangents;
  90557. },
  90558. enumerable: true,
  90559. configurable: true
  90560. });
  90561. /**
  90562. * Affects position data to this target
  90563. * @param data defines the position data to use
  90564. */
  90565. MorphTarget.prototype.setPositions = function (data) {
  90566. this._positions = data;
  90567. };
  90568. /**
  90569. * Gets the position data stored in this target
  90570. * @returns a FloatArray containing the position data (or null if not present)
  90571. */
  90572. MorphTarget.prototype.getPositions = function () {
  90573. return this._positions;
  90574. };
  90575. /**
  90576. * Affects normal data to this target
  90577. * @param data defines the normal data to use
  90578. */
  90579. MorphTarget.prototype.setNormals = function (data) {
  90580. this._normals = data;
  90581. };
  90582. /**
  90583. * Gets the normal data stored in this target
  90584. * @returns a FloatArray containing the normal data (or null if not present)
  90585. */
  90586. MorphTarget.prototype.getNormals = function () {
  90587. return this._normals;
  90588. };
  90589. /**
  90590. * Affects tangent data to this target
  90591. * @param data defines the tangent data to use
  90592. */
  90593. MorphTarget.prototype.setTangents = function (data) {
  90594. this._tangents = data;
  90595. };
  90596. /**
  90597. * Gets the tangent data stored in this target
  90598. * @returns a FloatArray containing the tangent data (or null if not present)
  90599. */
  90600. MorphTarget.prototype.getTangents = function () {
  90601. return this._tangents;
  90602. };
  90603. /**
  90604. * Serializes the current target into a Serialization object
  90605. * @returns the serialized object
  90606. */
  90607. MorphTarget.prototype.serialize = function () {
  90608. var serializationObject = {};
  90609. serializationObject.name = this.name;
  90610. serializationObject.influence = this.influence;
  90611. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90612. if (this.hasNormals) {
  90613. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90614. }
  90615. if (this.hasTangents) {
  90616. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90617. }
  90618. // Animations
  90619. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90620. return serializationObject;
  90621. };
  90622. // Statics
  90623. /**
  90624. * Creates a new target from serialized data
  90625. * @param serializationObject defines the serialized data to use
  90626. * @returns a new MorphTarget
  90627. */
  90628. MorphTarget.Parse = function (serializationObject) {
  90629. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90630. result.setPositions(serializationObject.positions);
  90631. if (serializationObject.normals) {
  90632. result.setNormals(serializationObject.normals);
  90633. }
  90634. if (serializationObject.tangents) {
  90635. result.setTangents(serializationObject.tangents);
  90636. }
  90637. // Animations
  90638. if (serializationObject.animations) {
  90639. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90640. var parsedAnimation = serializationObject.animations[animationIndex];
  90641. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90642. }
  90643. }
  90644. return result;
  90645. };
  90646. /**
  90647. * Creates a MorphTarget from mesh data
  90648. * @param mesh defines the source mesh
  90649. * @param name defines the name to use for the new target
  90650. * @param influence defines the influence to attach to the target
  90651. * @returns a new MorphTarget
  90652. */
  90653. MorphTarget.FromMesh = function (mesh, name, influence) {
  90654. if (!name) {
  90655. name = mesh.name;
  90656. }
  90657. var result = new MorphTarget(name, influence, mesh.getScene());
  90658. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90660. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90661. }
  90662. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90663. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90664. }
  90665. return result;
  90666. };
  90667. return MorphTarget;
  90668. }());
  90669. BABYLON.MorphTarget = MorphTarget;
  90670. })(BABYLON || (BABYLON = {}));
  90671. //# sourceMappingURL=babylon.morphTarget.js.map
  90672. var BABYLON;
  90673. (function (BABYLON) {
  90674. /**
  90675. * This class is used to deform meshes using morphing between different targets
  90676. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90677. */
  90678. var MorphTargetManager = /** @class */ (function () {
  90679. /**
  90680. * Creates a new MorphTargetManager
  90681. * @param scene defines the current scene
  90682. */
  90683. function MorphTargetManager(scene) {
  90684. if (scene === void 0) { scene = null; }
  90685. this._targets = new Array();
  90686. this._targetObservable = new Array();
  90687. this._activeTargets = new BABYLON.SmartArray(16);
  90688. this._supportsNormals = false;
  90689. this._supportsTangents = false;
  90690. this._vertexCount = 0;
  90691. this._uniqueId = 0;
  90692. this._tempInfluences = new Array();
  90693. if (!scene) {
  90694. scene = BABYLON.Engine.LastCreatedScene;
  90695. }
  90696. this._scene = scene;
  90697. if (this._scene) {
  90698. this._scene.morphTargetManagers.push(this);
  90699. this._uniqueId = this._scene.getUniqueId();
  90700. }
  90701. }
  90702. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90703. /**
  90704. * Gets the unique ID of this manager
  90705. */
  90706. get: function () {
  90707. return this._uniqueId;
  90708. },
  90709. enumerable: true,
  90710. configurable: true
  90711. });
  90712. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90713. /**
  90714. * Gets the number of vertices handled by this manager
  90715. */
  90716. get: function () {
  90717. return this._vertexCount;
  90718. },
  90719. enumerable: true,
  90720. configurable: true
  90721. });
  90722. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90723. /**
  90724. * Gets a boolean indicating if this manager supports morphing of normals
  90725. */
  90726. get: function () {
  90727. return this._supportsNormals;
  90728. },
  90729. enumerable: true,
  90730. configurable: true
  90731. });
  90732. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90733. /**
  90734. * Gets a boolean indicating if this manager supports morphing of tangents
  90735. */
  90736. get: function () {
  90737. return this._supportsTangents;
  90738. },
  90739. enumerable: true,
  90740. configurable: true
  90741. });
  90742. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90743. /**
  90744. * Gets the number of targets stored in this manager
  90745. */
  90746. get: function () {
  90747. return this._targets.length;
  90748. },
  90749. enumerable: true,
  90750. configurable: true
  90751. });
  90752. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90753. /**
  90754. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90755. */
  90756. get: function () {
  90757. return this._activeTargets.length;
  90758. },
  90759. enumerable: true,
  90760. configurable: true
  90761. });
  90762. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90763. /**
  90764. * Gets the list of influences (one per target)
  90765. */
  90766. get: function () {
  90767. return this._influences;
  90768. },
  90769. enumerable: true,
  90770. configurable: true
  90771. });
  90772. /**
  90773. * Gets the active target at specified index. An active target is a target with an influence > 0
  90774. * @param index defines the index to check
  90775. * @returns the requested target
  90776. */
  90777. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90778. return this._activeTargets.data[index];
  90779. };
  90780. /**
  90781. * Gets the target at specified index
  90782. * @param index defines the index to check
  90783. * @returns the requested target
  90784. */
  90785. MorphTargetManager.prototype.getTarget = function (index) {
  90786. return this._targets[index];
  90787. };
  90788. /**
  90789. * Add a new target to this manager
  90790. * @param target defines the target to add
  90791. */
  90792. MorphTargetManager.prototype.addTarget = function (target) {
  90793. var _this = this;
  90794. this._targets.push(target);
  90795. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90796. _this._syncActiveTargets(needUpdate);
  90797. }));
  90798. this._syncActiveTargets(true);
  90799. };
  90800. /**
  90801. * Removes a target from the manager
  90802. * @param target defines the target to remove
  90803. */
  90804. MorphTargetManager.prototype.removeTarget = function (target) {
  90805. var index = this._targets.indexOf(target);
  90806. if (index >= 0) {
  90807. this._targets.splice(index, 1);
  90808. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90809. this._syncActiveTargets(true);
  90810. }
  90811. };
  90812. /**
  90813. * Serializes the current manager into a Serialization object
  90814. * @returns the serialized object
  90815. */
  90816. MorphTargetManager.prototype.serialize = function () {
  90817. var serializationObject = {};
  90818. serializationObject.id = this.uniqueId;
  90819. serializationObject.targets = [];
  90820. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90821. var target = _a[_i];
  90822. serializationObject.targets.push(target.serialize());
  90823. }
  90824. return serializationObject;
  90825. };
  90826. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90827. var influenceCount = 0;
  90828. this._activeTargets.reset();
  90829. this._supportsNormals = true;
  90830. this._supportsTangents = true;
  90831. this._vertexCount = 0;
  90832. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90833. var target = _a[_i];
  90834. this._activeTargets.push(target);
  90835. this._tempInfluences[influenceCount++] = target.influence;
  90836. var positions = target.getPositions();
  90837. if (positions) {
  90838. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90839. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90840. var vertexCount = positions.length / 3;
  90841. if (this._vertexCount === 0) {
  90842. this._vertexCount = vertexCount;
  90843. }
  90844. else if (this._vertexCount !== vertexCount) {
  90845. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90846. return;
  90847. }
  90848. }
  90849. }
  90850. if (!this._influences || this._influences.length !== influenceCount) {
  90851. this._influences = new Float32Array(influenceCount);
  90852. }
  90853. for (var index = 0; index < influenceCount; index++) {
  90854. this._influences[index] = this._tempInfluences[index];
  90855. }
  90856. if (needUpdate) {
  90857. this.synchronize();
  90858. }
  90859. };
  90860. /**
  90861. * Syncrhonize the targets with all the meshes using this morph target manager
  90862. */
  90863. MorphTargetManager.prototype.synchronize = function () {
  90864. if (!this._scene) {
  90865. return;
  90866. }
  90867. // Flag meshes as dirty to resync with the active targets
  90868. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90869. var mesh = _a[_i];
  90870. if (mesh.morphTargetManager === this) {
  90871. mesh._syncGeometryWithMorphTargetManager();
  90872. }
  90873. }
  90874. };
  90875. // Statics
  90876. /**
  90877. * Creates a new MorphTargetManager from serialized data
  90878. * @param serializationObject defines the serialized data
  90879. * @param scene defines the hosting scene
  90880. * @returns the new MorphTargetManager
  90881. */
  90882. MorphTargetManager.Parse = function (serializationObject, scene) {
  90883. var result = new MorphTargetManager(scene);
  90884. result._uniqueId = serializationObject.id;
  90885. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90886. var targetData = _a[_i];
  90887. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90888. }
  90889. return result;
  90890. };
  90891. return MorphTargetManager;
  90892. }());
  90893. BABYLON.MorphTargetManager = MorphTargetManager;
  90894. })(BABYLON || (BABYLON = {}));
  90895. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90896. var BABYLON;
  90897. (function (BABYLON) {
  90898. var Octree = /** @class */ (function () {
  90899. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90900. if (maxDepth === void 0) { maxDepth = 2; }
  90901. this.maxDepth = maxDepth;
  90902. this.dynamicContent = new Array();
  90903. this._maxBlockCapacity = maxBlockCapacity || 64;
  90904. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90905. this._creationFunc = creationFunc;
  90906. }
  90907. // Methods
  90908. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90909. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90910. };
  90911. Octree.prototype.addMesh = function (entry) {
  90912. for (var index = 0; index < this.blocks.length; index++) {
  90913. var block = this.blocks[index];
  90914. block.addEntry(entry);
  90915. }
  90916. };
  90917. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90918. this._selectionContent.reset();
  90919. for (var index = 0; index < this.blocks.length; index++) {
  90920. var block = this.blocks[index];
  90921. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90922. }
  90923. if (allowDuplicate) {
  90924. this._selectionContent.concat(this.dynamicContent);
  90925. }
  90926. else {
  90927. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90928. }
  90929. return this._selectionContent;
  90930. };
  90931. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90932. this._selectionContent.reset();
  90933. for (var index = 0; index < this.blocks.length; index++) {
  90934. var block = this.blocks[index];
  90935. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90936. }
  90937. if (allowDuplicate) {
  90938. this._selectionContent.concat(this.dynamicContent);
  90939. }
  90940. else {
  90941. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90942. }
  90943. return this._selectionContent;
  90944. };
  90945. Octree.prototype.intersectsRay = function (ray) {
  90946. this._selectionContent.reset();
  90947. for (var index = 0; index < this.blocks.length; index++) {
  90948. var block = this.blocks[index];
  90949. block.intersectsRay(ray, this._selectionContent);
  90950. }
  90951. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90952. return this._selectionContent;
  90953. };
  90954. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90955. target.blocks = new Array();
  90956. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90957. // Segmenting space
  90958. for (var x = 0; x < 2; x++) {
  90959. for (var y = 0; y < 2; y++) {
  90960. for (var z = 0; z < 2; z++) {
  90961. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90962. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90963. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90964. block.addEntries(entries);
  90965. target.blocks.push(block);
  90966. }
  90967. }
  90968. }
  90969. };
  90970. Octree.CreationFuncForMeshes = function (entry, block) {
  90971. var boundingInfo = entry.getBoundingInfo();
  90972. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90973. block.entries.push(entry);
  90974. }
  90975. };
  90976. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90977. var boundingInfo = entry.getBoundingInfo();
  90978. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90979. block.entries.push(entry);
  90980. }
  90981. };
  90982. return Octree;
  90983. }());
  90984. BABYLON.Octree = Octree;
  90985. })(BABYLON || (BABYLON = {}));
  90986. //# sourceMappingURL=babylon.octree.js.map
  90987. var BABYLON;
  90988. (function (BABYLON) {
  90989. var OctreeBlock = /** @class */ (function () {
  90990. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90991. this.entries = new Array();
  90992. this._boundingVectors = new Array();
  90993. this._capacity = capacity;
  90994. this._depth = depth;
  90995. this._maxDepth = maxDepth;
  90996. this._creationFunc = creationFunc;
  90997. this._minPoint = minPoint;
  90998. this._maxPoint = maxPoint;
  90999. this._boundingVectors.push(minPoint.clone());
  91000. this._boundingVectors.push(maxPoint.clone());
  91001. this._boundingVectors.push(minPoint.clone());
  91002. this._boundingVectors[2].x = maxPoint.x;
  91003. this._boundingVectors.push(minPoint.clone());
  91004. this._boundingVectors[3].y = maxPoint.y;
  91005. this._boundingVectors.push(minPoint.clone());
  91006. this._boundingVectors[4].z = maxPoint.z;
  91007. this._boundingVectors.push(maxPoint.clone());
  91008. this._boundingVectors[5].z = minPoint.z;
  91009. this._boundingVectors.push(maxPoint.clone());
  91010. this._boundingVectors[6].x = minPoint.x;
  91011. this._boundingVectors.push(maxPoint.clone());
  91012. this._boundingVectors[7].y = minPoint.y;
  91013. }
  91014. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91015. // Property
  91016. get: function () {
  91017. return this._capacity;
  91018. },
  91019. enumerable: true,
  91020. configurable: true
  91021. });
  91022. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91023. get: function () {
  91024. return this._minPoint;
  91025. },
  91026. enumerable: true,
  91027. configurable: true
  91028. });
  91029. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91030. get: function () {
  91031. return this._maxPoint;
  91032. },
  91033. enumerable: true,
  91034. configurable: true
  91035. });
  91036. // Methods
  91037. OctreeBlock.prototype.addEntry = function (entry) {
  91038. if (this.blocks) {
  91039. for (var index = 0; index < this.blocks.length; index++) {
  91040. var block = this.blocks[index];
  91041. block.addEntry(entry);
  91042. }
  91043. return;
  91044. }
  91045. this._creationFunc(entry, this);
  91046. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91047. this.createInnerBlocks();
  91048. }
  91049. };
  91050. OctreeBlock.prototype.addEntries = function (entries) {
  91051. for (var index = 0; index < entries.length; index++) {
  91052. var mesh = entries[index];
  91053. this.addEntry(mesh);
  91054. }
  91055. };
  91056. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91057. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91058. if (this.blocks) {
  91059. for (var index = 0; index < this.blocks.length; index++) {
  91060. var block = this.blocks[index];
  91061. block.select(frustumPlanes, selection, allowDuplicate);
  91062. }
  91063. return;
  91064. }
  91065. if (allowDuplicate) {
  91066. selection.concat(this.entries);
  91067. }
  91068. else {
  91069. selection.concatWithNoDuplicate(this.entries);
  91070. }
  91071. }
  91072. };
  91073. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91074. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91075. if (this.blocks) {
  91076. for (var index = 0; index < this.blocks.length; index++) {
  91077. var block = this.blocks[index];
  91078. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91079. }
  91080. return;
  91081. }
  91082. if (allowDuplicate) {
  91083. selection.concat(this.entries);
  91084. }
  91085. else {
  91086. selection.concatWithNoDuplicate(this.entries);
  91087. }
  91088. }
  91089. };
  91090. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91091. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91092. if (this.blocks) {
  91093. for (var index = 0; index < this.blocks.length; index++) {
  91094. var block = this.blocks[index];
  91095. block.intersectsRay(ray, selection);
  91096. }
  91097. return;
  91098. }
  91099. selection.concatWithNoDuplicate(this.entries);
  91100. }
  91101. };
  91102. OctreeBlock.prototype.createInnerBlocks = function () {
  91103. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91104. };
  91105. return OctreeBlock;
  91106. }());
  91107. BABYLON.OctreeBlock = OctreeBlock;
  91108. })(BABYLON || (BABYLON = {}));
  91109. //# sourceMappingURL=babylon.octreeBlock.js.map
  91110. var BABYLON;
  91111. (function (BABYLON) {
  91112. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91113. __extends(VRDistortionCorrectionPostProcess, _super);
  91114. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91115. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91116. 'LensCenter',
  91117. 'Scale',
  91118. 'ScaleIn',
  91119. 'HmdWarpParam'
  91120. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91121. _this._isRightEye = isRightEye;
  91122. _this._distortionFactors = vrMetrics.distortionK;
  91123. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91124. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91125. _this.adaptScaleToCurrentViewport = true;
  91126. _this.onSizeChangedObservable.add(function () {
  91127. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91128. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91129. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91130. });
  91131. _this.onApplyObservable.add(function (effect) {
  91132. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91133. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91134. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91135. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91136. });
  91137. return _this;
  91138. }
  91139. return VRDistortionCorrectionPostProcess;
  91140. }(BABYLON.PostProcess));
  91141. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91142. })(BABYLON || (BABYLON = {}));
  91143. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91144. var BABYLON;
  91145. (function (BABYLON) {
  91146. /**
  91147. * Postprocess used to generate anaglyphic rendering
  91148. */
  91149. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91150. __extends(AnaglyphPostProcess, _super);
  91151. /**
  91152. * Creates a new AnaglyphPostProcess
  91153. * @param name defines postprocess name
  91154. * @param options defines creation options or target ratio scale
  91155. * @param rigCameras defines cameras using this postprocess
  91156. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91157. * @param engine defines hosting engine
  91158. * @param reusable defines if the postprocess will be reused multiple times per frame
  91159. */
  91160. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91161. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91162. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91163. _this.onApplyObservable.add(function (effect) {
  91164. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91165. });
  91166. return _this;
  91167. }
  91168. return AnaglyphPostProcess;
  91169. }(BABYLON.PostProcess));
  91170. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91171. })(BABYLON || (BABYLON = {}));
  91172. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91173. var BABYLON;
  91174. (function (BABYLON) {
  91175. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91176. __extends(StereoscopicInterlacePostProcess, _super);
  91177. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91178. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91179. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91180. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91181. _this.onSizeChangedObservable.add(function () {
  91182. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91183. });
  91184. _this.onApplyObservable.add(function (effect) {
  91185. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91186. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91187. });
  91188. return _this;
  91189. }
  91190. return StereoscopicInterlacePostProcess;
  91191. }(BABYLON.PostProcess));
  91192. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91193. })(BABYLON || (BABYLON = {}));
  91194. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91195. var BABYLON;
  91196. (function (BABYLON) {
  91197. /**
  91198. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91199. * Screen rotation is taken into account.
  91200. */
  91201. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91202. function FreeCameraDeviceOrientationInput() {
  91203. var _this = this;
  91204. this._screenOrientationAngle = 0;
  91205. this._screenQuaternion = new BABYLON.Quaternion();
  91206. this._alpha = 0;
  91207. this._beta = 0;
  91208. this._gamma = 0;
  91209. this._orientationChanged = function () {
  91210. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91211. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91212. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91213. };
  91214. this._deviceOrientation = function (evt) {
  91215. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91216. _this._beta = evt.beta !== null ? evt.beta : 0;
  91217. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91218. };
  91219. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91220. this._orientationChanged();
  91221. }
  91222. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91223. get: function () {
  91224. return this._camera;
  91225. },
  91226. set: function (camera) {
  91227. this._camera = camera;
  91228. if (this._camera != null && !this._camera.rotationQuaternion) {
  91229. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91230. }
  91231. },
  91232. enumerable: true,
  91233. configurable: true
  91234. });
  91235. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91236. window.addEventListener("orientationchange", this._orientationChanged);
  91237. window.addEventListener("deviceorientation", this._deviceOrientation);
  91238. //In certain cases, the attach control is called AFTER orientation was changed,
  91239. //So this is needed.
  91240. this._orientationChanged();
  91241. };
  91242. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91243. window.removeEventListener("orientationchange", this._orientationChanged);
  91244. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91245. };
  91246. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91247. //if no device orientation provided, don't update the rotation.
  91248. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91249. if (!this._alpha)
  91250. return;
  91251. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91252. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91253. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91254. //Mirror on XY Plane
  91255. this._camera.rotationQuaternion.z *= -1;
  91256. this._camera.rotationQuaternion.w *= -1;
  91257. };
  91258. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91259. return "FreeCameraDeviceOrientationInput";
  91260. };
  91261. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91262. return "deviceOrientation";
  91263. };
  91264. return FreeCameraDeviceOrientationInput;
  91265. }());
  91266. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91267. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91268. })(BABYLON || (BABYLON = {}));
  91269. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91270. var BABYLON;
  91271. (function (BABYLON) {
  91272. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91273. function ArcRotateCameraVRDeviceOrientationInput() {
  91274. this.alphaCorrection = 1;
  91275. this.betaCorrection = 1;
  91276. this.gammaCorrection = 1;
  91277. this._alpha = 0;
  91278. this._gamma = 0;
  91279. this._dirty = false;
  91280. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91281. }
  91282. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91283. this.camera.attachControl(element, noPreventDefault);
  91284. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91285. };
  91286. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91287. if (evt.alpha !== null) {
  91288. this._alpha = +evt.alpha | 0;
  91289. }
  91290. if (evt.gamma !== null) {
  91291. this._gamma = +evt.gamma | 0;
  91292. }
  91293. this._dirty = true;
  91294. };
  91295. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91296. if (this._dirty) {
  91297. this._dirty = false;
  91298. if (this._gamma < 0) {
  91299. this._gamma = 180 + this._gamma;
  91300. }
  91301. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91302. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91303. }
  91304. };
  91305. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91306. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91307. };
  91308. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91309. return "ArcRotateCameraVRDeviceOrientationInput";
  91310. };
  91311. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91312. return "VRDeviceOrientation";
  91313. };
  91314. return ArcRotateCameraVRDeviceOrientationInput;
  91315. }());
  91316. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91317. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91318. })(BABYLON || (BABYLON = {}));
  91319. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91320. var BABYLON;
  91321. (function (BABYLON) {
  91322. var VRCameraMetrics = /** @class */ (function () {
  91323. function VRCameraMetrics() {
  91324. this.compensateDistortion = true;
  91325. }
  91326. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91327. get: function () {
  91328. return this.hResolution / (2 * this.vResolution);
  91329. },
  91330. enumerable: true,
  91331. configurable: true
  91332. });
  91333. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91334. get: function () {
  91335. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91336. },
  91337. enumerable: true,
  91338. configurable: true
  91339. });
  91340. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91341. get: function () {
  91342. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91343. var h = (4 * meters) / this.hScreenSize;
  91344. return BABYLON.Matrix.Translation(h, 0, 0);
  91345. },
  91346. enumerable: true,
  91347. configurable: true
  91348. });
  91349. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91350. get: function () {
  91351. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91352. var h = (4 * meters) / this.hScreenSize;
  91353. return BABYLON.Matrix.Translation(-h, 0, 0);
  91354. },
  91355. enumerable: true,
  91356. configurable: true
  91357. });
  91358. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91359. get: function () {
  91360. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91366. get: function () {
  91367. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91368. },
  91369. enumerable: true,
  91370. configurable: true
  91371. });
  91372. VRCameraMetrics.GetDefault = function () {
  91373. var result = new VRCameraMetrics();
  91374. result.hResolution = 1280;
  91375. result.vResolution = 800;
  91376. result.hScreenSize = 0.149759993;
  91377. result.vScreenSize = 0.0935999975;
  91378. result.vScreenCenter = 0.0467999987;
  91379. result.eyeToScreenDistance = 0.0410000011;
  91380. result.lensSeparationDistance = 0.0635000020;
  91381. result.interpupillaryDistance = 0.0640000030;
  91382. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91383. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91384. result.postProcessScaleFactor = 1.714605507808412;
  91385. result.lensCenterOffset = 0.151976421;
  91386. return result;
  91387. };
  91388. return VRCameraMetrics;
  91389. }());
  91390. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91391. })(BABYLON || (BABYLON = {}));
  91392. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91393. var BABYLON;
  91394. (function (BABYLON) {
  91395. /**
  91396. * This represents a WebVR camera.
  91397. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91398. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91399. */
  91400. var WebVRFreeCamera = /** @class */ (function (_super) {
  91401. __extends(WebVRFreeCamera, _super);
  91402. /**
  91403. * Instantiates a WebVRFreeCamera.
  91404. * @param name The name of the WebVRFreeCamera
  91405. * @param position The starting anchor position for the camera
  91406. * @param scene The scene the camera belongs to
  91407. * @param webVROptions a set of customizable options for the webVRCamera
  91408. */
  91409. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91410. if (webVROptions === void 0) { webVROptions = {}; }
  91411. var _this = _super.call(this, name, position, scene) || this;
  91412. _this.webVROptions = webVROptions;
  91413. /**
  91414. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91415. */
  91416. _this._vrDevice = null;
  91417. /**
  91418. * The rawPose of the vrDevice.
  91419. */
  91420. _this.rawPose = null;
  91421. _this._specsVersion = "1.1";
  91422. _this._attached = false;
  91423. _this._descendants = [];
  91424. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91425. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91426. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91427. _this._standingMatrix = null;
  91428. /**
  91429. * Represents device position in babylon space.
  91430. */
  91431. _this.devicePosition = BABYLON.Vector3.Zero();
  91432. /**
  91433. * Represents device rotation in babylon space.
  91434. */
  91435. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91436. /**
  91437. * The scale of the device to be used when translating from device space to babylon space.
  91438. */
  91439. _this.deviceScaleFactor = 1;
  91440. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91441. _this._worldToDevice = BABYLON.Matrix.Identity();
  91442. /**
  91443. * References to the webVR controllers for the vrDevice.
  91444. */
  91445. _this.controllers = [];
  91446. /**
  91447. * Emits an event when a controller is attached.
  91448. */
  91449. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91450. /**
  91451. * Emits an event when a controller's mesh has been loaded;
  91452. */
  91453. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91454. /**
  91455. * If the rig cameras be used as parent instead of this camera.
  91456. */
  91457. _this.rigParenting = true;
  91458. _this._defaultHeight = undefined;
  91459. _this._workingVector = BABYLON.Vector3.Zero();
  91460. _this._oneVector = BABYLON.Vector3.One();
  91461. _this._workingMatrix = BABYLON.Matrix.Identity();
  91462. _this._cache.position = BABYLON.Vector3.Zero();
  91463. if (webVROptions.defaultHeight) {
  91464. _this._defaultHeight = webVROptions.defaultHeight;
  91465. _this.position.y = _this._defaultHeight;
  91466. }
  91467. _this.minZ = 0.1;
  91468. //legacy support - the compensation boolean was removed.
  91469. if (arguments.length === 5) {
  91470. _this.webVROptions = arguments[4];
  91471. }
  91472. // default webVR options
  91473. if (_this.webVROptions.trackPosition == undefined) {
  91474. _this.webVROptions.trackPosition = true;
  91475. }
  91476. if (_this.webVROptions.controllerMeshes == undefined) {
  91477. _this.webVROptions.controllerMeshes = true;
  91478. }
  91479. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91480. _this.webVROptions.defaultLightingOnControllers = true;
  91481. }
  91482. _this.rotationQuaternion = new BABYLON.Quaternion();
  91483. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91484. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91485. }
  91486. //enable VR
  91487. var engine = _this.getEngine();
  91488. _this._onVREnabled = function (success) { if (success) {
  91489. _this.initControllers();
  91490. } };
  91491. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91492. engine.initWebVR().add(function (event) {
  91493. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91494. return;
  91495. }
  91496. _this._vrDevice = event.vrDisplay;
  91497. //reset the rig parameters.
  91498. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91499. if (_this._attached) {
  91500. _this.getEngine().enableVR();
  91501. }
  91502. });
  91503. if (typeof (VRFrameData) !== "undefined")
  91504. _this._frameData = new VRFrameData();
  91505. /**
  91506. * The idea behind the following lines:
  91507. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91508. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91509. * the second will not show it correctly.
  91510. *
  91511. * To solve this - each object that has the camera as parent will be added to a protected array.
  91512. * When the rig camera renders, it will take this array and set all of those to be its children.
  91513. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91514. * Amazing!
  91515. */
  91516. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91517. if (camera.parent === _this && _this.rigParenting) {
  91518. _this._descendants = _this.getDescendants(true, function (n) {
  91519. // don't take the cameras or the controllers!
  91520. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91521. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91522. return !isController && !isRigCamera;
  91523. });
  91524. _this._descendants.forEach(function (node) {
  91525. node.parent = camera;
  91526. });
  91527. }
  91528. });
  91529. scene.onAfterCameraRenderObservable.add(function (camera) {
  91530. if (camera.parent === _this && _this.rigParenting) {
  91531. _this._descendants.forEach(function (node) {
  91532. node.parent = _this;
  91533. });
  91534. }
  91535. });
  91536. return _this;
  91537. }
  91538. /**
  91539. * Gets the device distance from the ground in meters.
  91540. * @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.
  91541. */
  91542. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91543. if (this._standingMatrix) {
  91544. // Add standing matrix offset to get real offset from ground in room
  91545. this._standingMatrix.getTranslationToRef(this._workingVector);
  91546. return this._deviceRoomPosition.y + this._workingVector.y;
  91547. }
  91548. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91549. return this._defaultHeight || 0;
  91550. };
  91551. /**
  91552. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91553. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91554. */
  91555. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91556. var _this = this;
  91557. if (callback === void 0) { callback = function (bool) { }; }
  91558. // Use standing matrix if available
  91559. this.getEngine().initWebVRAsync().then(function (result) {
  91560. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91561. callback(false);
  91562. }
  91563. else {
  91564. _this._standingMatrix = new BABYLON.Matrix();
  91565. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91566. if (!_this.getScene().useRightHandedSystem) {
  91567. [2, 6, 8, 9, 14].forEach(function (num) {
  91568. if (_this._standingMatrix) {
  91569. _this._standingMatrix.m[num] *= -1;
  91570. }
  91571. });
  91572. }
  91573. callback(true);
  91574. }
  91575. });
  91576. };
  91577. /**
  91578. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91579. * @returns A promise with a boolean set to if the standing matrix is supported.
  91580. */
  91581. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91582. var _this = this;
  91583. return new Promise(function (res, rej) {
  91584. _this.useStandingMatrix(function (supported) {
  91585. res(supported);
  91586. });
  91587. });
  91588. };
  91589. /**
  91590. * Disposes the camera
  91591. */
  91592. WebVRFreeCamera.prototype.dispose = function () {
  91593. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91594. _super.prototype.dispose.call(this);
  91595. };
  91596. /**
  91597. * Gets a vrController by name.
  91598. * @param name The name of the controller to retreive
  91599. * @returns the controller matching the name specified or null if not found
  91600. */
  91601. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91602. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91603. var gp = _a[_i];
  91604. if (gp.hand === name) {
  91605. return gp;
  91606. }
  91607. }
  91608. return null;
  91609. };
  91610. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91611. /**
  91612. * The controller corrisponding to the users left hand.
  91613. */
  91614. get: function () {
  91615. if (!this._leftController) {
  91616. this._leftController = this.getControllerByName("left");
  91617. }
  91618. return this._leftController;
  91619. },
  91620. enumerable: true,
  91621. configurable: true
  91622. });
  91623. ;
  91624. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91625. /**
  91626. * The controller corrisponding to the users right hand.
  91627. */
  91628. get: function () {
  91629. if (!this._rightController) {
  91630. this._rightController = this.getControllerByName("right");
  91631. }
  91632. return this._rightController;
  91633. },
  91634. enumerable: true,
  91635. configurable: true
  91636. });
  91637. ;
  91638. /**
  91639. * Casts a ray forward from the vrCamera's gaze.
  91640. * @param length Length of the ray (default: 100)
  91641. * @returns the ray corrisponding to the gaze
  91642. */
  91643. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91644. if (length === void 0) { length = 100; }
  91645. if (this.leftCamera) {
  91646. // Use left eye to avoid computation to compute center on every call
  91647. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91648. }
  91649. else {
  91650. return _super.prototype.getForwardRay.call(this, length);
  91651. }
  91652. };
  91653. /**
  91654. * Updates the camera based on device's frame data
  91655. */
  91656. WebVRFreeCamera.prototype._checkInputs = function () {
  91657. if (this._vrDevice && this._vrDevice.isPresenting) {
  91658. this._vrDevice.getFrameData(this._frameData);
  91659. this.updateFromDevice(this._frameData.pose);
  91660. }
  91661. _super.prototype._checkInputs.call(this);
  91662. };
  91663. /**
  91664. * Updates the poseControlled values based on the input device pose.
  91665. * @param poseData Pose coming from the device
  91666. */
  91667. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91668. if (poseData && poseData.orientation) {
  91669. this.rawPose = poseData;
  91670. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91671. if (this.getScene().useRightHandedSystem) {
  91672. this._deviceRoomRotationQuaternion.z *= -1;
  91673. this._deviceRoomRotationQuaternion.w *= -1;
  91674. }
  91675. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91676. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91677. if (this.getScene().useRightHandedSystem) {
  91678. this._deviceRoomPosition.z *= -1;
  91679. }
  91680. }
  91681. }
  91682. };
  91683. /**
  91684. * WebVR's attach control will start broadcasting frames to the device.
  91685. * Note that in certain browsers (chrome for example) this function must be called
  91686. * within a user-interaction callback. Example:
  91687. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91688. *
  91689. * @param element html element to attach the vrDevice to
  91690. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91691. */
  91692. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91693. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91694. this._attached = true;
  91695. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91696. if (this._vrDevice) {
  91697. this.getEngine().enableVR();
  91698. }
  91699. };
  91700. /**
  91701. * Detaches the camera from the html element and disables VR
  91702. *
  91703. * @param element html element to detach from
  91704. */
  91705. WebVRFreeCamera.prototype.detachControl = function (element) {
  91706. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91707. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91708. _super.prototype.detachControl.call(this, element);
  91709. this._attached = false;
  91710. this.getEngine().disableVR();
  91711. };
  91712. /**
  91713. * @returns the name of this class
  91714. */
  91715. WebVRFreeCamera.prototype.getClassName = function () {
  91716. return "WebVRFreeCamera";
  91717. };
  91718. /**
  91719. * Calls resetPose on the vrDisplay
  91720. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91721. */
  91722. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91723. //uses the vrDisplay's "resetPose()".
  91724. //pitch and roll won't be affected.
  91725. this._vrDevice.resetPose();
  91726. };
  91727. /**
  91728. * Updates the rig cameras (left and right eye)
  91729. */
  91730. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91731. var camLeft = this._rigCameras[0];
  91732. var camRight = this._rigCameras[1];
  91733. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91734. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91735. camLeft.position.copyFrom(this._deviceRoomPosition);
  91736. camRight.position.copyFrom(this._deviceRoomPosition);
  91737. };
  91738. /**
  91739. * Updates the cached values of the camera
  91740. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91741. */
  91742. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91743. var _this = this;
  91744. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91745. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91746. if (!this.updateCacheCalled) {
  91747. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91748. this.updateCacheCalled = true;
  91749. this.update();
  91750. }
  91751. // Set working vector to the device position in room space rotated by the new rotation
  91752. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91753. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91754. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91755. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91756. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91757. // Add translation from anchor position
  91758. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91759. this._workingVector.addInPlace(this.position);
  91760. this._workingVector.subtractInPlace(this._cache.position);
  91761. this._deviceToWorld.setTranslation(this._workingVector);
  91762. // Set an inverted matrix to be used when updating the camera
  91763. this._deviceToWorld.invertToRef(this._worldToDevice);
  91764. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91765. this.controllers.forEach(function (controller) {
  91766. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91767. controller.update();
  91768. });
  91769. }
  91770. if (!ignoreParentClass) {
  91771. _super.prototype._updateCache.call(this);
  91772. }
  91773. this.updateCacheCalled = false;
  91774. };
  91775. /**
  91776. * Updates the current device position and rotation in the babylon world
  91777. */
  91778. WebVRFreeCamera.prototype.update = function () {
  91779. // Get current device position in babylon world
  91780. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91781. // Get current device rotation in babylon world
  91782. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91783. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91784. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91785. _super.prototype.update.call(this);
  91786. };
  91787. /**
  91788. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91789. * @returns an identity matrix
  91790. */
  91791. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91792. return BABYLON.Matrix.Identity();
  91793. };
  91794. /**
  91795. * This function is called by the two RIG cameras.
  91796. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91797. */
  91798. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91799. var _this = this;
  91800. // Update the parent camera prior to using a child camera to avoid desynchronization
  91801. var parentCamera = this._cameraRigParams["parentCamera"];
  91802. parentCamera._updateCache();
  91803. //WebVR 1.1
  91804. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91805. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91806. if (!this.getScene().useRightHandedSystem) {
  91807. [2, 6, 8, 9, 14].forEach(function (num) {
  91808. _this._webvrViewMatrix.m[num] *= -1;
  91809. });
  91810. }
  91811. // update the camera rotation matrix
  91812. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91813. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91814. // Computing target and final matrix
  91815. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91816. // should the view matrix be updated with scale and position offset?
  91817. if (parentCamera.deviceScaleFactor !== 1) {
  91818. this._webvrViewMatrix.invert();
  91819. // scale the position, if set
  91820. if (parentCamera.deviceScaleFactor) {
  91821. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91822. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91823. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91824. }
  91825. this._webvrViewMatrix.invert();
  91826. }
  91827. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91828. // Compute global position
  91829. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91830. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91831. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91832. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91833. this._markSyncedWithParent();
  91834. return this._webvrViewMatrix;
  91835. };
  91836. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91837. var _this = this;
  91838. var parentCamera = this.parent;
  91839. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91840. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91841. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91842. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91843. //babylon compatible matrix
  91844. if (!this.getScene().useRightHandedSystem) {
  91845. [8, 9, 10, 11].forEach(function (num) {
  91846. _this._projectionMatrix.m[num] *= -1;
  91847. });
  91848. }
  91849. return this._projectionMatrix;
  91850. };
  91851. /**
  91852. * Initializes the controllers and their meshes
  91853. */
  91854. WebVRFreeCamera.prototype.initControllers = function () {
  91855. var _this = this;
  91856. this.controllers = [];
  91857. var manager = this.getScene().gamepadManager;
  91858. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91859. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91860. var webVrController = gamepad;
  91861. if (webVrController.defaultModel) {
  91862. webVrController.defaultModel.setEnabled(false);
  91863. }
  91864. if (webVrController.hand === "right") {
  91865. _this._rightController = null;
  91866. }
  91867. if (webVrController.hand === "left") {
  91868. _this._leftController = null;
  91869. }
  91870. var controllerIndex = _this.controllers.indexOf(webVrController);
  91871. if (controllerIndex !== -1) {
  91872. _this.controllers.splice(controllerIndex, 1);
  91873. }
  91874. }
  91875. });
  91876. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91877. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91878. var webVrController_1 = gamepad;
  91879. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91880. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91881. if (_this.webVROptions.controllerMeshes) {
  91882. if (webVrController_1.defaultModel) {
  91883. webVrController_1.defaultModel.setEnabled(true);
  91884. }
  91885. else {
  91886. // Load the meshes
  91887. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91888. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91889. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91890. if (_this.webVROptions.defaultLightingOnControllers) {
  91891. if (!_this._lightOnControllers) {
  91892. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91893. }
  91894. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91895. var children = mesh.getChildren();
  91896. if (children.length !== 0) {
  91897. children.forEach(function (mesh) {
  91898. light.includedOnlyMeshes.push(mesh);
  91899. activateLightOnSubMeshes_1(mesh, light);
  91900. });
  91901. }
  91902. };
  91903. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91904. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91905. }
  91906. });
  91907. }
  91908. }
  91909. webVrController_1.attachToPoseControlledCamera(_this);
  91910. // since this is async - sanity check. Is the controller already stored?
  91911. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91912. //add to the controllers array
  91913. _this.controllers.push(webVrController_1);
  91914. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91915. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91916. // So we're overriding setting left & right manually to be sure
  91917. var firstViveWandDetected = false;
  91918. for (var i = 0; i < _this.controllers.length; i++) {
  91919. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91920. if (!firstViveWandDetected) {
  91921. firstViveWandDetected = true;
  91922. _this.controllers[i].hand = "left";
  91923. }
  91924. else {
  91925. _this.controllers[i].hand = "right";
  91926. }
  91927. }
  91928. }
  91929. //did we find enough controllers? Great! let the developer know.
  91930. if (_this.controllers.length >= 2) {
  91931. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91932. }
  91933. }
  91934. }
  91935. });
  91936. };
  91937. return WebVRFreeCamera;
  91938. }(BABYLON.FreeCamera));
  91939. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91940. })(BABYLON || (BABYLON = {}));
  91941. //# sourceMappingURL=babylon.webVRCamera.js.map
  91942. var BABYLON;
  91943. (function (BABYLON) {
  91944. // We're mainly based on the logic defined into the FreeCamera code
  91945. /**
  91946. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91947. * being tilted forward or back and left or right.
  91948. */
  91949. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91950. __extends(DeviceOrientationCamera, _super);
  91951. /**
  91952. * Creates a new device orientation camera
  91953. * @param name The name of the camera
  91954. * @param position The start position camera
  91955. * @param scene The scene the camera belongs to
  91956. */
  91957. function DeviceOrientationCamera(name, position, scene) {
  91958. var _this = _super.call(this, name, position, scene) || this;
  91959. _this._quaternionCache = new BABYLON.Quaternion();
  91960. _this.inputs.addDeviceOrientation();
  91961. return _this;
  91962. }
  91963. /**
  91964. * Gets the current instance class name ("DeviceOrientationCamera").
  91965. * This helps avoiding instanceof at run time.
  91966. * @returns the class name
  91967. */
  91968. DeviceOrientationCamera.prototype.getClassName = function () {
  91969. return "DeviceOrientationCamera";
  91970. };
  91971. /**
  91972. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91973. */
  91974. DeviceOrientationCamera.prototype._checkInputs = function () {
  91975. _super.prototype._checkInputs.call(this);
  91976. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91977. if (this._initialQuaternion) {
  91978. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91979. }
  91980. };
  91981. /**
  91982. * Reset the camera to its default orientation on the specified axis only.
  91983. * @param axis The axis to reset
  91984. */
  91985. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91986. var _this = this;
  91987. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91988. //can only work if this camera has a rotation quaternion already.
  91989. if (!this.rotationQuaternion)
  91990. return;
  91991. if (!this._initialQuaternion) {
  91992. this._initialQuaternion = new BABYLON.Quaternion();
  91993. }
  91994. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91995. ['x', 'y', 'z'].forEach(function (axisName) {
  91996. if (!axis[axisName]) {
  91997. _this._initialQuaternion[axisName] = 0;
  91998. }
  91999. else {
  92000. _this._initialQuaternion[axisName] *= -1;
  92001. }
  92002. });
  92003. this._initialQuaternion.normalize();
  92004. //force rotation update
  92005. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92006. };
  92007. return DeviceOrientationCamera;
  92008. }(BABYLON.FreeCamera));
  92009. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92010. })(BABYLON || (BABYLON = {}));
  92011. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92012. var BABYLON;
  92013. (function (BABYLON) {
  92014. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92015. __extends(VRDeviceOrientationFreeCamera, _super);
  92016. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92017. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92018. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92019. var _this = _super.call(this, name, position, scene) || this;
  92020. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92021. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92022. return _this;
  92023. }
  92024. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92025. return "VRDeviceOrientationFreeCamera";
  92026. };
  92027. return VRDeviceOrientationFreeCamera;
  92028. }(BABYLON.DeviceOrientationCamera));
  92029. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92030. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92031. __extends(VRDeviceOrientationGamepadCamera, _super);
  92032. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92033. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92034. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92035. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92036. _this.inputs.addGamepad();
  92037. return _this;
  92038. }
  92039. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92040. return "VRDeviceOrientationGamepadCamera";
  92041. };
  92042. return VRDeviceOrientationGamepadCamera;
  92043. }(VRDeviceOrientationFreeCamera));
  92044. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92045. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92046. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92047. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92048. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92049. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92050. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92051. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92052. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92053. _this.inputs.addVRDeviceOrientation();
  92054. return _this;
  92055. }
  92056. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92057. return "VRDeviceOrientationArcRotateCamera";
  92058. };
  92059. return VRDeviceOrientationArcRotateCamera;
  92060. }(BABYLON.ArcRotateCamera));
  92061. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92062. })(BABYLON || (BABYLON = {}));
  92063. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  92064. var BABYLON;
  92065. (function (BABYLON) {
  92066. /**
  92067. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92068. */
  92069. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92070. __extends(AnaglyphFreeCamera, _super);
  92071. /**
  92072. * Creates a new AnaglyphFreeCamera
  92073. * @param name defines camera name
  92074. * @param position defines initial position
  92075. * @param interaxialDistance defines distance between each color axis
  92076. * @param scene defines the hosting scene
  92077. */
  92078. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92079. var _this = _super.call(this, name, position, scene) || this;
  92080. _this.interaxialDistance = interaxialDistance;
  92081. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92082. return _this;
  92083. }
  92084. /**
  92085. * Gets camera class name
  92086. * @returns AnaglyphFreeCamera
  92087. */
  92088. AnaglyphFreeCamera.prototype.getClassName = function () {
  92089. return "AnaglyphFreeCamera";
  92090. };
  92091. return AnaglyphFreeCamera;
  92092. }(BABYLON.FreeCamera));
  92093. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92094. /**
  92095. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92096. */
  92097. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92098. __extends(AnaglyphArcRotateCamera, _super);
  92099. /**
  92100. * Creates a new AnaglyphArcRotateCamera
  92101. * @param name defines camera name
  92102. * @param alpha defines alpha angle (in radians)
  92103. * @param beta defines beta angle (in radians)
  92104. * @param radius defines radius
  92105. * @param target defines camera target
  92106. * @param interaxialDistance defines distance between each color axis
  92107. * @param scene defines the hosting scene
  92108. */
  92109. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92110. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92111. _this.interaxialDistance = interaxialDistance;
  92112. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92113. return _this;
  92114. }
  92115. /**
  92116. * Gets camera class name
  92117. * @returns AnaglyphArcRotateCamera
  92118. */
  92119. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92120. return "AnaglyphArcRotateCamera";
  92121. };
  92122. return AnaglyphArcRotateCamera;
  92123. }(BABYLON.ArcRotateCamera));
  92124. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92125. /**
  92126. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92127. */
  92128. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92129. __extends(AnaglyphGamepadCamera, _super);
  92130. /**
  92131. * Creates a new AnaglyphGamepadCamera
  92132. * @param name defines camera name
  92133. * @param position defines initial position
  92134. * @param interaxialDistance defines distance between each color axis
  92135. * @param scene defines the hosting scene
  92136. */
  92137. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92138. var _this = _super.call(this, name, position, scene) || this;
  92139. _this.interaxialDistance = interaxialDistance;
  92140. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92141. return _this;
  92142. }
  92143. /**
  92144. * Gets camera class name
  92145. * @returns AnaglyphGamepadCamera
  92146. */
  92147. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92148. return "AnaglyphGamepadCamera";
  92149. };
  92150. return AnaglyphGamepadCamera;
  92151. }(BABYLON.GamepadCamera));
  92152. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92153. /**
  92154. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92155. */
  92156. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92157. __extends(AnaglyphUniversalCamera, _super);
  92158. /**
  92159. * Creates a new AnaglyphUniversalCamera
  92160. * @param name defines camera name
  92161. * @param position defines initial position
  92162. * @param interaxialDistance defines distance between each color axis
  92163. * @param scene defines the hosting scene
  92164. */
  92165. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92166. var _this = _super.call(this, name, position, scene) || this;
  92167. _this.interaxialDistance = interaxialDistance;
  92168. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92169. return _this;
  92170. }
  92171. /**
  92172. * Gets camera class name
  92173. * @returns AnaglyphUniversalCamera
  92174. */
  92175. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92176. return "AnaglyphUniversalCamera";
  92177. };
  92178. return AnaglyphUniversalCamera;
  92179. }(BABYLON.UniversalCamera));
  92180. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92181. /**
  92182. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92183. */
  92184. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92185. __extends(StereoscopicFreeCamera, _super);
  92186. /**
  92187. * Creates a new StereoscopicFreeCamera
  92188. * @param name defines camera name
  92189. * @param position defines initial position
  92190. * @param interaxialDistance defines distance between each color axis
  92191. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92192. * @param scene defines the hosting scene
  92193. */
  92194. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92195. var _this = _super.call(this, name, position, scene) || this;
  92196. _this.interaxialDistance = interaxialDistance;
  92197. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92198. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92199. return _this;
  92200. }
  92201. /**
  92202. * Gets camera class name
  92203. * @returns StereoscopicFreeCamera
  92204. */
  92205. StereoscopicFreeCamera.prototype.getClassName = function () {
  92206. return "StereoscopicFreeCamera";
  92207. };
  92208. return StereoscopicFreeCamera;
  92209. }(BABYLON.FreeCamera));
  92210. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92211. /**
  92212. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92213. */
  92214. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92215. __extends(StereoscopicArcRotateCamera, _super);
  92216. /**
  92217. * Creates a new StereoscopicArcRotateCamera
  92218. * @param name defines camera name
  92219. * @param alpha defines alpha angle (in radians)
  92220. * @param beta defines beta angle (in radians)
  92221. * @param radius defines radius
  92222. * @param target defines camera target
  92223. * @param interaxialDistance defines distance between each color axis
  92224. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92225. * @param scene defines the hosting scene
  92226. */
  92227. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92228. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92229. _this.interaxialDistance = interaxialDistance;
  92230. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92231. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92232. return _this;
  92233. }
  92234. /**
  92235. * Gets camera class name
  92236. * @returns StereoscopicArcRotateCamera
  92237. */
  92238. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92239. return "StereoscopicArcRotateCamera";
  92240. };
  92241. return StereoscopicArcRotateCamera;
  92242. }(BABYLON.ArcRotateCamera));
  92243. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92244. /**
  92245. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92246. */
  92247. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92248. __extends(StereoscopicGamepadCamera, _super);
  92249. /**
  92250. * Creates a new StereoscopicGamepadCamera
  92251. * @param name defines camera name
  92252. * @param position defines initial position
  92253. * @param interaxialDistance defines distance between each color axis
  92254. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92255. * @param scene defines the hosting scene
  92256. */
  92257. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92258. var _this = _super.call(this, name, position, scene) || this;
  92259. _this.interaxialDistance = interaxialDistance;
  92260. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92261. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92262. return _this;
  92263. }
  92264. /**
  92265. * Gets camera class name
  92266. * @returns StereoscopicGamepadCamera
  92267. */
  92268. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92269. return "StereoscopicGamepadCamera";
  92270. };
  92271. return StereoscopicGamepadCamera;
  92272. }(BABYLON.GamepadCamera));
  92273. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92274. /**
  92275. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92276. */
  92277. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92278. __extends(StereoscopicUniversalCamera, _super);
  92279. /**
  92280. * Creates a new StereoscopicUniversalCamera
  92281. * @param name defines camera name
  92282. * @param position defines initial position
  92283. * @param interaxialDistance defines distance between each color axis
  92284. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92285. * @param scene defines the hosting scene
  92286. */
  92287. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92288. var _this = _super.call(this, name, position, scene) || this;
  92289. _this.interaxialDistance = interaxialDistance;
  92290. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92291. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92292. return _this;
  92293. }
  92294. /**
  92295. * Gets camera class name
  92296. * @returns StereoscopicUniversalCamera
  92297. */
  92298. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92299. return "StereoscopicUniversalCamera";
  92300. };
  92301. return StereoscopicUniversalCamera;
  92302. }(BABYLON.UniversalCamera));
  92303. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92304. })(BABYLON || (BABYLON = {}));
  92305. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  92306. var BABYLON;
  92307. (function (BABYLON) {
  92308. var VRExperienceHelperGazer = /** @class */ (function () {
  92309. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92310. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92311. this.scene = scene;
  92312. this._pointerDownOnMeshAsked = false;
  92313. this._isActionableMesh = false;
  92314. this._teleportationRequestInitiated = false;
  92315. this._teleportationBackRequestInitiated = false;
  92316. this._rotationRightAsked = false;
  92317. this._rotationLeftAsked = false;
  92318. this._dpadPressed = true;
  92319. this._activePointer = false;
  92320. this._id = VRExperienceHelperGazer._idCounter++;
  92321. // Gaze tracker
  92322. if (!gazeTrackerToClone) {
  92323. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92324. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92325. this._gazeTracker.isPickable = false;
  92326. this._gazeTracker.isVisible = false;
  92327. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92328. targetMat.specularColor = BABYLON.Color3.Black();
  92329. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92330. targetMat.backFaceCulling = false;
  92331. this._gazeTracker.material = targetMat;
  92332. }
  92333. else {
  92334. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92335. }
  92336. }
  92337. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92338. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92339. };
  92340. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92341. this._pointerDownOnMeshAsked = true;
  92342. if (this._currentHit) {
  92343. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92344. }
  92345. };
  92346. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92347. if (this._currentHit) {
  92348. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92349. }
  92350. this._pointerDownOnMeshAsked = false;
  92351. };
  92352. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92353. this._activePointer = true;
  92354. };
  92355. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92356. this._activePointer = false;
  92357. };
  92358. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92359. if (distance === void 0) { distance = 100; }
  92360. };
  92361. VRExperienceHelperGazer.prototype.dispose = function () {
  92362. this._interactionsEnabled = false;
  92363. this._teleportationEnabled = false;
  92364. if (this._gazeTracker) {
  92365. this._gazeTracker.dispose();
  92366. }
  92367. };
  92368. VRExperienceHelperGazer._idCounter = 0;
  92369. return VRExperienceHelperGazer;
  92370. }());
  92371. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92372. __extends(VRExperienceHelperControllerGazer, _super);
  92373. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92374. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92375. _this.webVRController = webVRController;
  92376. // Laser pointer
  92377. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92378. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92379. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92380. laserPointerMaterial.alpha = 0.6;
  92381. _this._laserPointer.material = laserPointerMaterial;
  92382. _this._laserPointer.rotation.x = Math.PI / 2;
  92383. _this._laserPointer.position.z = -0.5;
  92384. _this._laserPointer.isVisible = false;
  92385. _this._laserPointer.isPickable = false;
  92386. if (!webVRController.mesh) {
  92387. // Create an empty mesh that is used prior to loading the high quality model
  92388. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92389. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92390. preloadPointerPose.rotation.x = -0.7;
  92391. preloadMesh.addChild(preloadPointerPose);
  92392. webVRController.attachToMesh(preloadMesh);
  92393. }
  92394. _this._setLaserPointerParent(webVRController.mesh);
  92395. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92396. _this._setLaserPointerParent(mesh);
  92397. });
  92398. return _this;
  92399. }
  92400. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92401. return this.webVRController.getForwardRay(length);
  92402. };
  92403. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92404. _super.prototype._activatePointer.call(this);
  92405. this._laserPointer.isVisible = true;
  92406. };
  92407. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92408. _super.prototype._deactivatePointer.call(this);
  92409. this._laserPointer.isVisible = false;
  92410. };
  92411. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92412. this._laserPointer.material.emissiveColor = color;
  92413. };
  92414. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92415. var makeNotPick = function (root) {
  92416. root.name += " laserPointer";
  92417. root.isPickable = false;
  92418. root.getChildMeshes().forEach(function (c) {
  92419. makeNotPick(c);
  92420. });
  92421. };
  92422. makeNotPick(mesh);
  92423. var childMeshes = mesh.getChildMeshes();
  92424. this.webVRController._pointingPoseNode = null;
  92425. for (var i = 0; i < childMeshes.length; i++) {
  92426. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92427. mesh = childMeshes[i];
  92428. this.webVRController._pointingPoseNode = mesh;
  92429. break;
  92430. }
  92431. }
  92432. this._laserPointer.parent = mesh;
  92433. };
  92434. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92435. if (distance === void 0) { distance = 100; }
  92436. this._laserPointer.scaling.y = distance;
  92437. this._laserPointer.position.z = -distance / 2;
  92438. };
  92439. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92440. _super.prototype.dispose.call(this);
  92441. this._laserPointer.dispose();
  92442. if (this._meshAttachedObserver) {
  92443. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92444. }
  92445. };
  92446. return VRExperienceHelperControllerGazer;
  92447. }(VRExperienceHelperGazer));
  92448. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92449. __extends(VRExperienceHelperCameraGazer, _super);
  92450. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92451. var _this = _super.call(this, scene) || this;
  92452. _this.getCamera = getCamera;
  92453. return _this;
  92454. }
  92455. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92456. var camera = this.getCamera();
  92457. if (camera) {
  92458. return camera.getForwardRay(length);
  92459. }
  92460. else {
  92461. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92462. }
  92463. };
  92464. return VRExperienceHelperCameraGazer;
  92465. }(VRExperienceHelperGazer));
  92466. /**
  92467. * Helps to quickly add VR support to an existing scene.
  92468. * See http://doc.babylonjs.com/how_to/webvr_helper
  92469. */
  92470. var VRExperienceHelper = /** @class */ (function () {
  92471. /**
  92472. * Instantiates a VRExperienceHelper.
  92473. * Helps to quickly add VR support to an existing scene.
  92474. * @param scene The scene the VRExperienceHelper belongs to.
  92475. * @param webVROptions Options to modify the vr experience helper's behavior.
  92476. */
  92477. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92478. if (webVROptions === void 0) { webVROptions = {}; }
  92479. var _this = this;
  92480. this.webVROptions = webVROptions;
  92481. // Can the system support WebVR, even if a headset isn't plugged in?
  92482. this._webVRsupported = false;
  92483. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92484. this._webVRready = false;
  92485. // Are we waiting for the requestPresent callback to complete?
  92486. this._webVRrequesting = false;
  92487. // Are we presenting to the headset right now?
  92488. this._webVRpresenting = false;
  92489. // Are we presenting in the fullscreen fallback?
  92490. this._fullscreenVRpresenting = false;
  92491. /**
  92492. * Observable raised when entering VR.
  92493. */
  92494. this.onEnteringVRObservable = new BABYLON.Observable();
  92495. /**
  92496. * Observable raised when exiting VR.
  92497. */
  92498. this.onExitingVRObservable = new BABYLON.Observable();
  92499. /**
  92500. * Observable raised when controller mesh is loaded.
  92501. */
  92502. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92503. this._useCustomVRButton = false;
  92504. this._teleportationRequested = false;
  92505. this._teleportActive = false;
  92506. this._floorMeshesCollection = [];
  92507. this._rotationAllowed = true;
  92508. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92509. this._isDefaultTeleportationTarget = true;
  92510. this._teleportationFillColor = "#444444";
  92511. this._teleportationBorderColor = "#FFFFFF";
  92512. this._rotationAngle = 0;
  92513. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92514. this._padSensibilityUp = 0.65;
  92515. this._padSensibilityDown = 0.35;
  92516. this.leftController = null;
  92517. this.rightController = null;
  92518. /**
  92519. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92520. */
  92521. this.onNewMeshSelected = new BABYLON.Observable();
  92522. /**
  92523. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92524. */
  92525. this.onNewMeshPicked = new BABYLON.Observable();
  92526. /**
  92527. * Observable raised before camera teleportation
  92528. */
  92529. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92530. /**
  92531. * Observable raised after camera teleportation
  92532. */
  92533. this.onAfterCameraTeleport = new BABYLON.Observable();
  92534. /**
  92535. * Observable raised when current selected mesh gets unselected
  92536. */
  92537. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92538. /**
  92539. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92540. */
  92541. this.teleportationEnabled = true;
  92542. this._teleportationInitialized = false;
  92543. this._interactionsEnabled = false;
  92544. this._interactionsRequested = false;
  92545. this._displayGaze = true;
  92546. this._displayLaserPointer = true;
  92547. this._onResize = function () {
  92548. _this.moveButtonToBottomRight();
  92549. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92550. _this.exitVR();
  92551. }
  92552. };
  92553. this._onFullscreenChange = function () {
  92554. if (document.fullscreen !== undefined) {
  92555. _this._fullscreenVRpresenting = document.fullscreen;
  92556. }
  92557. else if (document.mozFullScreen !== undefined) {
  92558. _this._fullscreenVRpresenting = document.mozFullScreen;
  92559. }
  92560. else if (document.webkitIsFullScreen !== undefined) {
  92561. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92562. }
  92563. else if (document.msIsFullScreen !== undefined) {
  92564. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92565. }
  92566. else if (document.msFullscreenElement !== undefined) {
  92567. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92568. }
  92569. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92570. _this.exitVR();
  92571. if (!_this._useCustomVRButton) {
  92572. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92573. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92574. }
  92575. }
  92576. };
  92577. this.beforeRender = function () {
  92578. if (_this.leftController && _this.leftController._activePointer) {
  92579. _this._castRayAndSelectObject(_this.leftController);
  92580. }
  92581. if (_this.rightController && _this.rightController._activePointer) {
  92582. _this._castRayAndSelectObject(_this.rightController);
  92583. }
  92584. if (_this._noControllerIsActive) {
  92585. _this._castRayAndSelectObject(_this._cameraGazer);
  92586. }
  92587. else {
  92588. _this._cameraGazer._gazeTracker.isVisible = false;
  92589. }
  92590. };
  92591. this._onNewGamepadConnected = function (gamepad) {
  92592. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92593. if (gamepad.leftStick) {
  92594. gamepad.onleftstickchanged(function (stickValues) {
  92595. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92596. // Listening to classic/xbox gamepad only if no VR controller is active
  92597. if ((!_this.leftController && !_this.rightController) ||
  92598. ((_this.leftController && !_this.leftController._activePointer) &&
  92599. (_this.rightController && !_this.rightController._activePointer))) {
  92600. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92601. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92602. }
  92603. }
  92604. });
  92605. }
  92606. if (gamepad.rightStick) {
  92607. gamepad.onrightstickchanged(function (stickValues) {
  92608. if (_this._teleportationInitialized) {
  92609. _this._checkRotate(stickValues, _this._cameraGazer);
  92610. }
  92611. });
  92612. }
  92613. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92614. gamepad.onbuttondown(function (buttonPressed) {
  92615. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92616. _this._cameraGazer._selectionPointerDown();
  92617. }
  92618. });
  92619. gamepad.onbuttonup(function (buttonPressed) {
  92620. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92621. _this._cameraGazer._selectionPointerUp();
  92622. }
  92623. });
  92624. }
  92625. }
  92626. else {
  92627. var webVRController = gamepad;
  92628. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92629. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92630. _this.rightController = controller;
  92631. }
  92632. else {
  92633. _this.leftController = controller;
  92634. }
  92635. _this._tryEnableInteractionOnController(controller);
  92636. }
  92637. };
  92638. // 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
  92639. this._tryEnableInteractionOnController = function (controller) {
  92640. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92641. _this._enableInteractionOnController(controller);
  92642. }
  92643. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92644. _this._enableTeleportationOnController(controller);
  92645. }
  92646. };
  92647. this._onNewGamepadDisconnected = function (gamepad) {
  92648. if (gamepad instanceof BABYLON.WebVRController) {
  92649. if (gamepad.hand === "left" && _this.leftController != null) {
  92650. _this.leftController.dispose();
  92651. _this.leftController = null;
  92652. }
  92653. if (gamepad.hand === "right" && _this.rightController != null) {
  92654. _this.rightController.dispose();
  92655. _this.rightController = null;
  92656. }
  92657. }
  92658. };
  92659. this._workingVector = BABYLON.Vector3.Zero();
  92660. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92661. this._workingMatrix = BABYLON.Matrix.Identity();
  92662. this._scene = scene;
  92663. this._canvas = scene.getEngine().getRenderingCanvas();
  92664. // Parse options
  92665. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92666. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92667. }
  92668. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92669. webVROptions.createDeviceOrientationCamera = true;
  92670. }
  92671. if (webVROptions.laserToggle === undefined) {
  92672. webVROptions.laserToggle = true;
  92673. }
  92674. if (webVROptions.defaultHeight === undefined) {
  92675. webVROptions.defaultHeight = 1.7;
  92676. }
  92677. if (webVROptions.useCustomVRButton) {
  92678. this._useCustomVRButton = true;
  92679. if (webVROptions.customVRButton) {
  92680. this._btnVR = webVROptions.customVRButton;
  92681. }
  92682. }
  92683. if (webVROptions.rayLength) {
  92684. this._rayLength = webVROptions.rayLength;
  92685. }
  92686. this._defaultHeight = webVROptions.defaultHeight;
  92687. if (webVROptions.positionScale) {
  92688. this._rayLength *= webVROptions.positionScale;
  92689. this._defaultHeight *= webVROptions.positionScale;
  92690. }
  92691. // Set position
  92692. if (this._scene.activeCamera) {
  92693. this._position = this._scene.activeCamera.position.clone();
  92694. }
  92695. else {
  92696. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92697. }
  92698. // Set non-vr camera
  92699. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92700. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92701. // Copy data from existing camera
  92702. if (this._scene.activeCamera) {
  92703. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92704. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92705. // Set rotation from previous camera
  92706. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92707. var targetCamera = this._scene.activeCamera;
  92708. if (targetCamera.rotationQuaternion) {
  92709. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92710. }
  92711. else {
  92712. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92713. }
  92714. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92715. }
  92716. }
  92717. this._scene.activeCamera = this._deviceOrientationCamera;
  92718. if (this._canvas) {
  92719. this._scene.activeCamera.attachControl(this._canvas);
  92720. }
  92721. }
  92722. else {
  92723. this._existingCamera = this._scene.activeCamera;
  92724. }
  92725. // Create VR cameras
  92726. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92727. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92728. }
  92729. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92730. this._webVRCamera.useStandingMatrix();
  92731. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92732. // Create default button
  92733. if (!this._useCustomVRButton) {
  92734. this._btnVR = document.createElement("BUTTON");
  92735. this._btnVR.className = "babylonVRicon";
  92736. this._btnVR.id = "babylonVRiconbtn";
  92737. this._btnVR.title = "Click to switch to VR";
  92738. 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) }";
  92739. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92740. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92741. // css += ".babylonVRicon.vrdisplaysupported { }";
  92742. // css += ".babylonVRicon.vrdisplayready { }";
  92743. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92744. var style = document.createElement('style');
  92745. style.appendChild(document.createTextNode(css));
  92746. document.getElementsByTagName('head')[0].appendChild(style);
  92747. this.moveButtonToBottomRight();
  92748. }
  92749. // VR button click event
  92750. if (this._btnVR) {
  92751. this._btnVR.addEventListener("click", function () {
  92752. if (!_this.isInVRMode) {
  92753. _this.enterVR();
  92754. }
  92755. else {
  92756. _this.exitVR();
  92757. }
  92758. });
  92759. }
  92760. // Window events
  92761. window.addEventListener("resize", this._onResize);
  92762. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92763. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92764. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92765. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92766. document.onmsfullscreenchange = this._onFullscreenChange;
  92767. // Display vr button when headset is connected
  92768. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92769. this.displayVRButton();
  92770. }
  92771. else {
  92772. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92773. if (e.vrDisplay) {
  92774. _this.displayVRButton();
  92775. }
  92776. });
  92777. }
  92778. // Exiting VR mode using 'ESC' key on desktop
  92779. this._onKeyDown = function (event) {
  92780. if (event.keyCode === 27 && _this.isInVRMode) {
  92781. _this.exitVR();
  92782. }
  92783. };
  92784. document.addEventListener("keydown", this._onKeyDown);
  92785. // Exiting VR mode double tapping the touch screen
  92786. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92787. if (_this.isInVRMode) {
  92788. _this.exitVR();
  92789. if (_this._fullscreenVRpresenting) {
  92790. _this._scene.getEngine().switchFullscreen(true);
  92791. }
  92792. }
  92793. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92794. // Listen for WebVR display changes
  92795. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92796. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92797. this._onVRRequestPresentStart = function () {
  92798. _this._webVRrequesting = true;
  92799. _this.updateButtonVisibility();
  92800. };
  92801. this._onVRRequestPresentComplete = function (success) {
  92802. _this._webVRrequesting = false;
  92803. _this.updateButtonVisibility();
  92804. };
  92805. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92806. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92807. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92808. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92809. scene.onDisposeObservable.add(function () {
  92810. _this.dispose();
  92811. });
  92812. // Gamepad connection events
  92813. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92814. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92815. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92816. this.updateButtonVisibility();
  92817. //create easing functions
  92818. this._circleEase = new BABYLON.CircleEase();
  92819. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92820. if (this.webVROptions.floorMeshes) {
  92821. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92822. }
  92823. }
  92824. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92825. /** Return this.onEnteringVRObservable
  92826. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92827. */
  92828. get: function () {
  92829. return this.onEnteringVRObservable;
  92830. },
  92831. enumerable: true,
  92832. configurable: true
  92833. });
  92834. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92835. /** Return this.onExitingVRObservable
  92836. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92837. */
  92838. get: function () {
  92839. return this.onExitingVRObservable;
  92840. },
  92841. enumerable: true,
  92842. configurable: true
  92843. });
  92844. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92845. /** Return this.onControllerMeshLoadedObservable
  92846. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92847. */
  92848. get: function () {
  92849. return this.onControllerMeshLoadedObservable;
  92850. },
  92851. enumerable: true,
  92852. configurable: true
  92853. });
  92854. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92855. /**
  92856. * The mesh used to display where the user is going to teleport.
  92857. */
  92858. get: function () {
  92859. return this._teleportationTarget;
  92860. },
  92861. /**
  92862. * Sets the mesh to be used to display where the user is going to teleport.
  92863. */
  92864. set: function (value) {
  92865. if (value) {
  92866. value.name = "teleportationTarget";
  92867. this._isDefaultTeleportationTarget = false;
  92868. this._teleportationTarget = value;
  92869. }
  92870. },
  92871. enumerable: true,
  92872. configurable: true
  92873. });
  92874. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92875. /**
  92876. * The mesh used to display where the user is selecting,
  92877. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92878. * See http://doc.babylonjs.com/resources/baking_transformations
  92879. */
  92880. get: function () {
  92881. return this._cameraGazer._gazeTracker;
  92882. },
  92883. set: function (value) {
  92884. if (value) {
  92885. this._cameraGazer._gazeTracker = value;
  92886. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92887. this._cameraGazer._gazeTracker.isPickable = false;
  92888. this._cameraGazer._gazeTracker.isVisible = false;
  92889. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92890. if (this.leftController) {
  92891. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92892. }
  92893. if (this.rightController) {
  92894. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92895. }
  92896. }
  92897. },
  92898. enumerable: true,
  92899. configurable: true
  92900. });
  92901. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92902. /**
  92903. * If the ray of the gaze should be displayed.
  92904. */
  92905. get: function () {
  92906. return this._displayGaze;
  92907. },
  92908. /**
  92909. * Sets if the ray of the gaze should be displayed.
  92910. */
  92911. set: function (value) {
  92912. this._displayGaze = value;
  92913. if (!value) {
  92914. this._cameraGazer._gazeTracker.isVisible = false;
  92915. if (this.leftController) {
  92916. this.leftController._gazeTracker.isVisible = false;
  92917. }
  92918. if (this.rightController) {
  92919. this.rightController._gazeTracker.isVisible = false;
  92920. }
  92921. }
  92922. },
  92923. enumerable: true,
  92924. configurable: true
  92925. });
  92926. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92927. /**
  92928. * If the ray of the LaserPointer should be displayed.
  92929. */
  92930. get: function () {
  92931. return this._displayLaserPointer;
  92932. },
  92933. /**
  92934. * Sets if the ray of the LaserPointer should be displayed.
  92935. */
  92936. set: function (value) {
  92937. this._displayLaserPointer = value;
  92938. if (!value) {
  92939. if (this.rightController) {
  92940. this.rightController._deactivatePointer();
  92941. this.rightController._gazeTracker.isVisible = false;
  92942. }
  92943. if (this.leftController) {
  92944. this.leftController._deactivatePointer();
  92945. this.leftController._gazeTracker.isVisible = false;
  92946. }
  92947. }
  92948. else {
  92949. if (this.rightController) {
  92950. this.rightController._activatePointer();
  92951. }
  92952. if (this.leftController) {
  92953. this.leftController._activatePointer();
  92954. }
  92955. }
  92956. },
  92957. enumerable: true,
  92958. configurable: true
  92959. });
  92960. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92961. /**
  92962. * The deviceOrientationCamera used as the camera when not in VR.
  92963. */
  92964. get: function () {
  92965. return this._deviceOrientationCamera;
  92966. },
  92967. enumerable: true,
  92968. configurable: true
  92969. });
  92970. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92971. /**
  92972. * Based on the current WebVR support, returns the current VR camera used.
  92973. */
  92974. get: function () {
  92975. if (this._webVRready) {
  92976. return this._webVRCamera;
  92977. }
  92978. else {
  92979. return this._scene.activeCamera;
  92980. }
  92981. },
  92982. enumerable: true,
  92983. configurable: true
  92984. });
  92985. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92986. /**
  92987. * The webVRCamera which is used when in VR.
  92988. */
  92989. get: function () {
  92990. return this._webVRCamera;
  92991. },
  92992. enumerable: true,
  92993. configurable: true
  92994. });
  92995. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92996. /**
  92997. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92998. */
  92999. get: function () {
  93000. return this._vrDeviceOrientationCamera;
  93001. },
  93002. enumerable: true,
  93003. configurable: true
  93004. });
  93005. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93006. get: function () {
  93007. var result = this._cameraGazer._teleportationRequestInitiated
  93008. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93009. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93010. return result;
  93011. },
  93012. enumerable: true,
  93013. configurable: true
  93014. });
  93015. // Raised when one of the controller has loaded successfully its associated default mesh
  93016. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93017. if (this.leftController && this.leftController.webVRController == webVRController) {
  93018. if (webVRController.mesh) {
  93019. this.leftController._setLaserPointerParent(webVRController.mesh);
  93020. }
  93021. }
  93022. if (this.rightController && this.rightController.webVRController == webVRController) {
  93023. if (webVRController.mesh) {
  93024. this.rightController._setLaserPointerParent(webVRController.mesh);
  93025. }
  93026. }
  93027. try {
  93028. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93029. }
  93030. catch (err) {
  93031. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93032. }
  93033. };
  93034. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93035. /**
  93036. * Gets a value indicating if we are currently in VR mode.
  93037. */
  93038. get: function () {
  93039. return this._webVRpresenting || this._fullscreenVRpresenting;
  93040. },
  93041. enumerable: true,
  93042. configurable: true
  93043. });
  93044. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93045. var vrDisplay = this._scene.getEngine().getVRDevice();
  93046. if (vrDisplay) {
  93047. var wasPresenting = this._webVRpresenting;
  93048. // A VR display is connected
  93049. this._webVRpresenting = vrDisplay.isPresenting;
  93050. if (wasPresenting && !this._webVRpresenting)
  93051. this.exitVR();
  93052. }
  93053. else {
  93054. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93055. }
  93056. this.updateButtonVisibility();
  93057. };
  93058. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93059. this._webVRsupported = eventArgs.vrSupported;
  93060. this._webVRready = !!eventArgs.vrDisplay;
  93061. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93062. this.updateButtonVisibility();
  93063. };
  93064. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93065. if (this._canvas && !this._useCustomVRButton) {
  93066. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93067. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93068. }
  93069. };
  93070. VRExperienceHelper.prototype.displayVRButton = function () {
  93071. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93072. document.body.appendChild(this._btnVR);
  93073. this._btnVRDisplayed = true;
  93074. }
  93075. };
  93076. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93077. if (!this._btnVR || this._useCustomVRButton) {
  93078. return;
  93079. }
  93080. this._btnVR.className = "babylonVRicon";
  93081. if (this.isInVRMode) {
  93082. this._btnVR.className += " vrdisplaypresenting";
  93083. }
  93084. else {
  93085. if (this._webVRready)
  93086. this._btnVR.className += " vrdisplayready";
  93087. if (this._webVRsupported)
  93088. this._btnVR.className += " vrdisplaysupported";
  93089. if (this._webVRrequesting)
  93090. this._btnVR.className += " vrdisplayrequesting";
  93091. }
  93092. };
  93093. /**
  93094. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93095. * Otherwise, will use the fullscreen API.
  93096. */
  93097. VRExperienceHelper.prototype.enterVR = function () {
  93098. if (this.onEnteringVRObservable) {
  93099. try {
  93100. this.onEnteringVRObservable.notifyObservers(this);
  93101. }
  93102. catch (err) {
  93103. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93104. }
  93105. }
  93106. if (this._scene.activeCamera) {
  93107. this._position = this._scene.activeCamera.position.clone();
  93108. // make sure that we return to the last active camera
  93109. this._existingCamera = this._scene.activeCamera;
  93110. }
  93111. if (this._webVRrequesting)
  93112. return;
  93113. // If WebVR is supported and a headset is connected
  93114. if (this._webVRready) {
  93115. if (!this._webVRpresenting) {
  93116. this._webVRCamera.position = this._position;
  93117. this._scene.activeCamera = this._webVRCamera;
  93118. }
  93119. }
  93120. else if (this._vrDeviceOrientationCamera) {
  93121. this._vrDeviceOrientationCamera.position = this._position;
  93122. if (this._scene.activeCamera) {
  93123. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93124. }
  93125. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93126. this._scene.getEngine().switchFullscreen(true);
  93127. this.updateButtonVisibility();
  93128. }
  93129. if (this._scene.activeCamera && this._canvas) {
  93130. this._scene.activeCamera.attachControl(this._canvas);
  93131. }
  93132. if (this._interactionsEnabled) {
  93133. this._scene.registerBeforeRender(this.beforeRender);
  93134. }
  93135. };
  93136. /**
  93137. * Attempt to exit VR, or fullscreen.
  93138. */
  93139. VRExperienceHelper.prototype.exitVR = function () {
  93140. if (this.onExitingVRObservable) {
  93141. try {
  93142. this.onExitingVRObservable.notifyObservers(this);
  93143. }
  93144. catch (err) {
  93145. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93146. }
  93147. }
  93148. if (this._webVRpresenting) {
  93149. this._scene.getEngine().disableVR();
  93150. }
  93151. if (this._scene.activeCamera) {
  93152. this._position = this._scene.activeCamera.position.clone();
  93153. }
  93154. if (this._deviceOrientationCamera) {
  93155. this._deviceOrientationCamera.position = this._position;
  93156. this._scene.activeCamera = this._deviceOrientationCamera;
  93157. if (this._canvas) {
  93158. this._scene.activeCamera.attachControl(this._canvas);
  93159. }
  93160. }
  93161. else if (this._existingCamera) {
  93162. this._existingCamera.position = this._position;
  93163. this._scene.activeCamera = this._existingCamera;
  93164. }
  93165. this.updateButtonVisibility();
  93166. if (this._interactionsEnabled) {
  93167. this._scene.unregisterBeforeRender(this.beforeRender);
  93168. }
  93169. // resize to update width and height when exiting vr exits fullscreen
  93170. this._scene.getEngine().resize();
  93171. };
  93172. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93173. /**
  93174. * The position of the vr experience helper.
  93175. */
  93176. get: function () {
  93177. return this._position;
  93178. },
  93179. /**
  93180. * Sets the position of the vr experience helper.
  93181. */
  93182. set: function (value) {
  93183. this._position = value;
  93184. if (this._scene.activeCamera) {
  93185. this._scene.activeCamera.position = value;
  93186. }
  93187. },
  93188. enumerable: true,
  93189. configurable: true
  93190. });
  93191. /**
  93192. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  93193. */
  93194. VRExperienceHelper.prototype.enableInteractions = function () {
  93195. var _this = this;
  93196. if (!this._interactionsEnabled) {
  93197. this._interactionsRequested = true;
  93198. if (this.leftController) {
  93199. this._enableInteractionOnController(this.leftController);
  93200. }
  93201. if (this.rightController) {
  93202. this._enableInteractionOnController(this.rightController);
  93203. }
  93204. this.raySelectionPredicate = function (mesh) {
  93205. return mesh.isVisible;
  93206. };
  93207. this.meshSelectionPredicate = function (mesh) {
  93208. return true;
  93209. };
  93210. this._raySelectionPredicate = function (mesh) {
  93211. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93212. && mesh.name.indexOf("teleportationTarget") === -1
  93213. && mesh.name.indexOf("torusTeleportation") === -1
  93214. && mesh.name.indexOf("laserPointer") === -1)) {
  93215. return _this.raySelectionPredicate(mesh);
  93216. }
  93217. return false;
  93218. };
  93219. this._interactionsEnabled = true;
  93220. }
  93221. };
  93222. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93223. get: function () {
  93224. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93225. },
  93226. enumerable: true,
  93227. configurable: true
  93228. });
  93229. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93230. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93231. if (this._floorMeshesCollection[i].id === mesh.id) {
  93232. return true;
  93233. }
  93234. }
  93235. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93236. return true;
  93237. }
  93238. return false;
  93239. };
  93240. /**
  93241. * Adds a floor mesh to be used for teleportation.
  93242. * @param floorMesh the mesh to be used for teleportation.
  93243. */
  93244. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93245. if (!this._floorMeshesCollection) {
  93246. return;
  93247. }
  93248. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93249. return;
  93250. }
  93251. this._floorMeshesCollection.push(floorMesh);
  93252. };
  93253. /**
  93254. * Removes a floor mesh from being used for teleportation.
  93255. * @param floorMesh the mesh to be removed.
  93256. */
  93257. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93258. if (!this._floorMeshesCollection) {
  93259. return;
  93260. }
  93261. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93262. if (meshIndex !== -1) {
  93263. this._floorMeshesCollection.splice(meshIndex, 1);
  93264. }
  93265. };
  93266. /**
  93267. * Enables interactions and teleportation using the VR controllers and gaze.
  93268. * @param vrTeleportationOptions options to modify teleportation behavior.
  93269. */
  93270. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93271. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93272. if (!this._teleportationInitialized) {
  93273. this._teleportationRequested = true;
  93274. this.enableInteractions();
  93275. if (vrTeleportationOptions.floorMeshName) {
  93276. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93277. }
  93278. if (vrTeleportationOptions.floorMeshes) {
  93279. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93280. }
  93281. if (this.leftController != null) {
  93282. this._enableTeleportationOnController(this.leftController);
  93283. }
  93284. if (this.rightController != null) {
  93285. this._enableTeleportationOnController(this.rightController);
  93286. }
  93287. // Creates an image processing post process for the vignette not relying
  93288. // on the main scene configuration for image processing to reduce setup and spaces
  93289. // (gamma/linear) conflicts.
  93290. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93291. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93292. imageProcessingConfiguration.vignetteEnabled = true;
  93293. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93294. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93295. this._teleportationInitialized = true;
  93296. if (this._isDefaultTeleportationTarget) {
  93297. this._createTeleportationCircles();
  93298. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93299. }
  93300. }
  93301. };
  93302. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93303. var _this = this;
  93304. var controllerMesh = controller.webVRController.mesh;
  93305. if (controllerMesh) {
  93306. controller._interactionsEnabled = true;
  93307. controller._activatePointer();
  93308. if (this.webVROptions.laserToggle) {
  93309. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93310. // Enabling / disabling laserPointer
  93311. if (_this._displayLaserPointer && stateObject.value === 1) {
  93312. if (controller._activePointer) {
  93313. controller._deactivatePointer();
  93314. }
  93315. else {
  93316. controller._activatePointer();
  93317. }
  93318. if (_this.displayGaze) {
  93319. controller._gazeTracker.isVisible = controller._activePointer;
  93320. }
  93321. }
  93322. });
  93323. }
  93324. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93325. var gazer = controller;
  93326. if (_this._noControllerIsActive) {
  93327. gazer = _this._cameraGazer;
  93328. }
  93329. if (!gazer._pointerDownOnMeshAsked) {
  93330. if (stateObject.value > _this._padSensibilityUp) {
  93331. gazer._selectionPointerDown();
  93332. }
  93333. }
  93334. else if (stateObject.value < _this._padSensibilityDown) {
  93335. gazer._selectionPointerUp();
  93336. }
  93337. });
  93338. }
  93339. };
  93340. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93341. // Dont teleport if another gaze already requested teleportation
  93342. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93343. return;
  93344. }
  93345. if (!gazer._teleportationRequestInitiated) {
  93346. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93347. gazer._activatePointer();
  93348. gazer._teleportationRequestInitiated = true;
  93349. }
  93350. }
  93351. else {
  93352. // Listening to the proper controller values changes to confirm teleportation
  93353. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93354. if (this._teleportActive) {
  93355. this._teleportCamera(this._haloCenter);
  93356. }
  93357. gazer._teleportationRequestInitiated = false;
  93358. }
  93359. }
  93360. };
  93361. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93362. // Only rotate when user is not currently selecting a teleportation location
  93363. if (gazer._teleportationRequestInitiated) {
  93364. return;
  93365. }
  93366. if (!gazer._rotationLeftAsked) {
  93367. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93368. gazer._rotationLeftAsked = true;
  93369. if (this._rotationAllowed) {
  93370. this._rotateCamera(false);
  93371. }
  93372. }
  93373. }
  93374. else {
  93375. if (stateObject.x > -this._padSensibilityDown) {
  93376. gazer._rotationLeftAsked = false;
  93377. }
  93378. }
  93379. if (!gazer._rotationRightAsked) {
  93380. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93381. gazer._rotationRightAsked = true;
  93382. if (this._rotationAllowed) {
  93383. this._rotateCamera(true);
  93384. }
  93385. }
  93386. }
  93387. else {
  93388. if (stateObject.x < this._padSensibilityDown) {
  93389. gazer._rotationRightAsked = false;
  93390. }
  93391. }
  93392. };
  93393. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93394. // Only teleport backwards when user is not currently selecting a teleportation location
  93395. if (gazer._teleportationRequestInitiated) {
  93396. return;
  93397. }
  93398. // Teleport backwards
  93399. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93400. if (!gazer._teleportationBackRequestInitiated) {
  93401. if (!this.currentVRCamera) {
  93402. return;
  93403. }
  93404. // Get rotation and position of the current camera
  93405. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93406. var position = this.currentVRCamera.position;
  93407. // If the camera has device position, use that instead
  93408. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93409. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93410. position = this.currentVRCamera.devicePosition;
  93411. }
  93412. // Get matrix with only the y rotation of the device rotation
  93413. rotation.toEulerAnglesToRef(this._workingVector);
  93414. this._workingVector.z = 0;
  93415. this._workingVector.x = 0;
  93416. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93417. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93418. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93419. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93420. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93421. var ray = new BABYLON.Ray(position, this._workingVector);
  93422. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93423. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93424. this._teleportCamera(hit.pickedPoint);
  93425. }
  93426. gazer._teleportationBackRequestInitiated = true;
  93427. }
  93428. }
  93429. else {
  93430. gazer._teleportationBackRequestInitiated = false;
  93431. }
  93432. };
  93433. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93434. var _this = this;
  93435. var controllerMesh = controller.webVRController.mesh;
  93436. if (controllerMesh) {
  93437. if (!controller._interactionsEnabled) {
  93438. this._enableInteractionOnController(controller);
  93439. }
  93440. controller._interactionsEnabled = true;
  93441. controller._teleportationEnabled = true;
  93442. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93443. controller._dpadPressed = false;
  93444. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93445. controller._dpadPressed = stateObject.pressed;
  93446. if (!controller._dpadPressed) {
  93447. controller._rotationLeftAsked = false;
  93448. controller._rotationRightAsked = false;
  93449. controller._teleportationBackRequestInitiated = false;
  93450. }
  93451. });
  93452. }
  93453. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93454. if (_this.teleportationEnabled) {
  93455. _this._checkTeleportBackwards(stateObject, controller);
  93456. _this._checkTeleportWithRay(stateObject, controller);
  93457. }
  93458. _this._checkRotate(stateObject, controller);
  93459. });
  93460. }
  93461. };
  93462. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93463. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93464. this._teleportationTarget.isPickable = false;
  93465. var length = 512;
  93466. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93467. dynamicTexture.hasAlpha = true;
  93468. var context = dynamicTexture.getContext();
  93469. var centerX = length / 2;
  93470. var centerY = length / 2;
  93471. var radius = 200;
  93472. context.beginPath();
  93473. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93474. context.fillStyle = this._teleportationFillColor;
  93475. context.fill();
  93476. context.lineWidth = 10;
  93477. context.strokeStyle = this._teleportationBorderColor;
  93478. context.stroke();
  93479. context.closePath();
  93480. dynamicTexture.update();
  93481. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93482. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93483. this._teleportationTarget.material = teleportationCircleMaterial;
  93484. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93485. torus.isPickable = false;
  93486. torus.parent = this._teleportationTarget;
  93487. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93488. var keys = [];
  93489. keys.push({
  93490. frame: 0,
  93491. value: 0
  93492. });
  93493. keys.push({
  93494. frame: 30,
  93495. value: 0.4
  93496. });
  93497. keys.push({
  93498. frame: 60,
  93499. value: 0
  93500. });
  93501. animationInnerCircle.setKeys(keys);
  93502. var easingFunction = new BABYLON.SineEase();
  93503. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93504. animationInnerCircle.setEasingFunction(easingFunction);
  93505. torus.animations = [];
  93506. torus.animations.push(animationInnerCircle);
  93507. this._scene.beginAnimation(torus, 0, 60, true);
  93508. this._hideTeleportationTarget();
  93509. };
  93510. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93511. this._teleportActive = true;
  93512. if (this._teleportationInitialized) {
  93513. this._teleportationTarget.isVisible = true;
  93514. if (this._isDefaultTeleportationTarget) {
  93515. this._teleportationTarget.getChildren()[0].isVisible = true;
  93516. }
  93517. }
  93518. };
  93519. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93520. this._teleportActive = false;
  93521. if (this._teleportationInitialized) {
  93522. this._teleportationTarget.isVisible = false;
  93523. if (this._isDefaultTeleportationTarget) {
  93524. this._teleportationTarget.getChildren()[0].isVisible = false;
  93525. }
  93526. }
  93527. };
  93528. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93529. var _this = this;
  93530. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93531. return;
  93532. }
  93533. if (right) {
  93534. this._rotationAngle++;
  93535. }
  93536. else {
  93537. this._rotationAngle--;
  93538. }
  93539. this.currentVRCamera.animations = [];
  93540. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93541. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93542. var animationRotationKeys = [];
  93543. animationRotationKeys.push({
  93544. frame: 0,
  93545. value: this.currentVRCamera.rotationQuaternion
  93546. });
  93547. animationRotationKeys.push({
  93548. frame: 6,
  93549. value: target
  93550. });
  93551. animationRotation.setKeys(animationRotationKeys);
  93552. animationRotation.setEasingFunction(this._circleEase);
  93553. this.currentVRCamera.animations.push(animationRotation);
  93554. this._postProcessMove.animations = [];
  93555. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93556. var vignetteWeightKeys = [];
  93557. vignetteWeightKeys.push({
  93558. frame: 0,
  93559. value: 0
  93560. });
  93561. vignetteWeightKeys.push({
  93562. frame: 3,
  93563. value: 4
  93564. });
  93565. vignetteWeightKeys.push({
  93566. frame: 6,
  93567. value: 0
  93568. });
  93569. animationPP.setKeys(vignetteWeightKeys);
  93570. animationPP.setEasingFunction(this._circleEase);
  93571. this._postProcessMove.animations.push(animationPP);
  93572. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93573. var vignetteStretchKeys = [];
  93574. vignetteStretchKeys.push({
  93575. frame: 0,
  93576. value: 0
  93577. });
  93578. vignetteStretchKeys.push({
  93579. frame: 3,
  93580. value: 10
  93581. });
  93582. vignetteStretchKeys.push({
  93583. frame: 6,
  93584. value: 0
  93585. });
  93586. animationPP2.setKeys(vignetteStretchKeys);
  93587. animationPP2.setEasingFunction(this._circleEase);
  93588. this._postProcessMove.animations.push(animationPP2);
  93589. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93590. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93591. this._postProcessMove.samples = 4;
  93592. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93593. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93594. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93595. });
  93596. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93597. };
  93598. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93599. if (hit.pickedPoint) {
  93600. if (gazer._teleportationRequestInitiated) {
  93601. this._displayTeleportationTarget();
  93602. this._haloCenter.copyFrom(hit.pickedPoint);
  93603. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93604. }
  93605. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93606. if (pickNormal) {
  93607. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93608. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93609. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93610. }
  93611. this._teleportationTarget.position.y += 0.1;
  93612. }
  93613. };
  93614. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93615. var _this = this;
  93616. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93617. return;
  93618. }
  93619. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93620. // offset of the headset from the anchor.
  93621. if (this.webVRCamera.leftCamera) {
  93622. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93623. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93624. location.subtractToRef(this._workingVector, this._workingVector);
  93625. }
  93626. else {
  93627. this._workingVector.copyFrom(location);
  93628. }
  93629. // Add height to account for user's height offset
  93630. if (this.isInVRMode) {
  93631. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93632. }
  93633. else {
  93634. this._workingVector.y += this._defaultHeight;
  93635. }
  93636. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93637. // Create animation from the camera's position to the new location
  93638. this.currentVRCamera.animations = [];
  93639. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93640. var animationCameraTeleportationKeys = [{
  93641. frame: 0,
  93642. value: this.currentVRCamera.position
  93643. },
  93644. {
  93645. frame: 11,
  93646. value: this._workingVector
  93647. }
  93648. ];
  93649. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93650. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93651. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93652. this._postProcessMove.animations = [];
  93653. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93654. var vignetteWeightKeys = [];
  93655. vignetteWeightKeys.push({
  93656. frame: 0,
  93657. value: 0
  93658. });
  93659. vignetteWeightKeys.push({
  93660. frame: 5,
  93661. value: 8
  93662. });
  93663. vignetteWeightKeys.push({
  93664. frame: 11,
  93665. value: 0
  93666. });
  93667. animationPP.setKeys(vignetteWeightKeys);
  93668. this._postProcessMove.animations.push(animationPP);
  93669. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93670. var vignetteStretchKeys = [];
  93671. vignetteStretchKeys.push({
  93672. frame: 0,
  93673. value: 0
  93674. });
  93675. vignetteStretchKeys.push({
  93676. frame: 5,
  93677. value: 10
  93678. });
  93679. vignetteStretchKeys.push({
  93680. frame: 11,
  93681. value: 0
  93682. });
  93683. animationPP2.setKeys(vignetteStretchKeys);
  93684. this._postProcessMove.animations.push(animationPP2);
  93685. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93686. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93687. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93688. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93689. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93690. });
  93691. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93692. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93693. });
  93694. this._hideTeleportationTarget();
  93695. };
  93696. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93697. if (normal) {
  93698. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93699. if (angle < Math.PI / 2) {
  93700. normal.scaleInPlace(-1);
  93701. }
  93702. }
  93703. return normal;
  93704. };
  93705. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93706. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93707. return;
  93708. }
  93709. var ray = gazer._getForwardRay(this._rayLength);
  93710. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93711. if (hit) {
  93712. // Populate the contrllers mesh that can be used for drag/drop
  93713. if (gazer._laserPointer) {
  93714. hit.originMesh = gazer._laserPointer.parent;
  93715. }
  93716. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93717. }
  93718. gazer._currentHit = hit;
  93719. // Moving the gazeTracker on the mesh face targetted
  93720. if (hit && hit.pickedPoint) {
  93721. if (this._displayGaze) {
  93722. var multiplier = 1;
  93723. gazer._gazeTracker.isVisible = true;
  93724. if (gazer._isActionableMesh) {
  93725. multiplier = 3;
  93726. }
  93727. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93728. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93729. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93730. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93731. // To avoid z-fighting
  93732. var deltaFighting = 0.002;
  93733. if (pickNormal) {
  93734. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93735. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93736. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93737. }
  93738. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93739. if (gazer._gazeTracker.position.x < 0) {
  93740. gazer._gazeTracker.position.x += deltaFighting;
  93741. }
  93742. else {
  93743. gazer._gazeTracker.position.x -= deltaFighting;
  93744. }
  93745. if (gazer._gazeTracker.position.y < 0) {
  93746. gazer._gazeTracker.position.y += deltaFighting;
  93747. }
  93748. else {
  93749. gazer._gazeTracker.position.y -= deltaFighting;
  93750. }
  93751. if (gazer._gazeTracker.position.z < 0) {
  93752. gazer._gazeTracker.position.z += deltaFighting;
  93753. }
  93754. else {
  93755. gazer._gazeTracker.position.z -= deltaFighting;
  93756. }
  93757. }
  93758. // Changing the size of the laser pointer based on the distance from the targetted point
  93759. gazer._updatePointerDistance(hit.distance);
  93760. }
  93761. else {
  93762. gazer._updatePointerDistance();
  93763. gazer._gazeTracker.isVisible = false;
  93764. }
  93765. if (hit && hit.pickedMesh) {
  93766. // The object selected is the floor, we're in a teleportation scenario
  93767. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93768. // Moving the teleportation area to this targetted point
  93769. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93770. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93771. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93772. }
  93773. gazer._currentMeshSelected = null;
  93774. if (gazer._teleportationRequestInitiated) {
  93775. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93776. }
  93777. return;
  93778. }
  93779. // If not, we're in a selection scenario
  93780. //this._teleportationAllowed = false;
  93781. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93782. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93783. this.onNewMeshPicked.notifyObservers(hit);
  93784. gazer._currentMeshSelected = hit.pickedMesh;
  93785. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93786. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93787. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93788. gazer._isActionableMesh = true;
  93789. }
  93790. else {
  93791. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93792. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93793. gazer._isActionableMesh = false;
  93794. }
  93795. try {
  93796. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93797. }
  93798. catch (err) {
  93799. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93800. }
  93801. }
  93802. else {
  93803. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93804. gazer._currentMeshSelected = null;
  93805. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93806. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93807. }
  93808. }
  93809. }
  93810. else {
  93811. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93812. gazer._currentMeshSelected = null;
  93813. //this._teleportationAllowed = false;
  93814. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93815. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93816. }
  93817. };
  93818. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93819. if (mesh) {
  93820. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93821. }
  93822. };
  93823. /**
  93824. * Sets the color of the laser ray from the vr controllers.
  93825. * @param color new color for the ray.
  93826. */
  93827. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93828. if (this.leftController) {
  93829. this.leftController._setLaserPointerColor(color);
  93830. }
  93831. if (this.rightController) {
  93832. this.rightController._setLaserPointerColor(color);
  93833. }
  93834. };
  93835. /**
  93836. * Sets the color of the ray from the vr headsets gaze.
  93837. * @param color new color for the ray.
  93838. */
  93839. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93840. if (!this._cameraGazer._gazeTracker.material) {
  93841. return;
  93842. }
  93843. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93844. if (this.leftController) {
  93845. this.leftController._gazeTracker.material.emissiveColor = color;
  93846. }
  93847. if (this.rightController) {
  93848. this.rightController._gazeTracker.material.emissiveColor = color;
  93849. }
  93850. };
  93851. /**
  93852. * Exits VR and disposes of the vr experience helper
  93853. */
  93854. VRExperienceHelper.prototype.dispose = function () {
  93855. if (this.isInVRMode) {
  93856. this.exitVR();
  93857. }
  93858. if (this._postProcessMove) {
  93859. this._postProcessMove.dispose();
  93860. }
  93861. if (this._webVRCamera) {
  93862. this._webVRCamera.dispose();
  93863. }
  93864. if (this._vrDeviceOrientationCamera) {
  93865. this._vrDeviceOrientationCamera.dispose();
  93866. }
  93867. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93868. document.body.removeChild(this._btnVR);
  93869. }
  93870. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93871. this._deviceOrientationCamera.dispose();
  93872. }
  93873. if (this._cameraGazer) {
  93874. this._cameraGazer.dispose();
  93875. }
  93876. if (this.leftController) {
  93877. this.leftController.dispose();
  93878. }
  93879. if (this.rightController) {
  93880. this.rightController.dispose();
  93881. }
  93882. if (this._teleportationTarget) {
  93883. this._teleportationTarget.dispose();
  93884. }
  93885. this._floorMeshesCollection = [];
  93886. document.removeEventListener("keydown", this._onKeyDown);
  93887. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93888. window.removeEventListener("resize", this._onResize);
  93889. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93890. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93891. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93892. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93893. document.onmsfullscreenchange = null;
  93894. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93895. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93896. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93897. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93898. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93899. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93900. this._scene.unregisterBeforeRender(this.beforeRender);
  93901. };
  93902. /**
  93903. * Gets the name of the VRExperienceHelper class
  93904. * @returns "VRExperienceHelper"
  93905. */
  93906. VRExperienceHelper.prototype.getClassName = function () {
  93907. return "VRExperienceHelper";
  93908. };
  93909. return VRExperienceHelper;
  93910. }());
  93911. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93912. })(BABYLON || (BABYLON = {}));
  93913. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93914. // Mainly based on these 2 articles :
  93915. // 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
  93916. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93917. var BABYLON;
  93918. (function (BABYLON) {
  93919. /**
  93920. * Defines the potential axis of a Joystick
  93921. */
  93922. var JoystickAxis;
  93923. (function (JoystickAxis) {
  93924. /** X axis */
  93925. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93926. /** Y axis */
  93927. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93928. /** Z axis */
  93929. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93930. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93931. /**
  93932. * Class used to define virtual joystick (used in touch mode)
  93933. */
  93934. var VirtualJoystick = /** @class */ (function () {
  93935. /**
  93936. * Creates a new virtual joystick
  93937. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93938. */
  93939. function VirtualJoystick(leftJoystick) {
  93940. var _this = this;
  93941. if (leftJoystick) {
  93942. this._leftJoystick = true;
  93943. }
  93944. else {
  93945. this._leftJoystick = false;
  93946. }
  93947. VirtualJoystick._globalJoystickIndex++;
  93948. // By default left & right arrow keys are moving the X
  93949. // and up & down keys are moving the Y
  93950. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93951. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93952. this.reverseLeftRight = false;
  93953. this.reverseUpDown = false;
  93954. // collections of pointers
  93955. this._touches = new BABYLON.StringDictionary();
  93956. this.deltaPosition = BABYLON.Vector3.Zero();
  93957. this._joystickSensibility = 25;
  93958. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93959. this._onResize = function (evt) {
  93960. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93961. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93962. if (VirtualJoystick.vjCanvas) {
  93963. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93964. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93965. }
  93966. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93967. };
  93968. // injecting a canvas element on top of the canvas 3D game
  93969. if (!VirtualJoystick.vjCanvas) {
  93970. window.addEventListener("resize", this._onResize, false);
  93971. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93972. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93973. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93974. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93975. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93976. VirtualJoystick.vjCanvas.style.width = "100%";
  93977. VirtualJoystick.vjCanvas.style.height = "100%";
  93978. VirtualJoystick.vjCanvas.style.position = "absolute";
  93979. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93980. VirtualJoystick.vjCanvas.style.top = "0px";
  93981. VirtualJoystick.vjCanvas.style.left = "0px";
  93982. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93983. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93984. // Support for jQuery PEP polyfill
  93985. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93986. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93987. if (!context) {
  93988. throw new Error("Unable to create canvas for virtual joystick");
  93989. }
  93990. VirtualJoystick.vjCanvasContext = context;
  93991. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93992. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93993. document.body.appendChild(VirtualJoystick.vjCanvas);
  93994. }
  93995. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93996. this.pressed = false;
  93997. // default joystick color
  93998. this._joystickColor = "cyan";
  93999. this._joystickPointerID = -1;
  94000. // current joystick position
  94001. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94002. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94003. // origin joystick position
  94004. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94005. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94006. this._onPointerDownHandlerRef = function (evt) {
  94007. _this._onPointerDown(evt);
  94008. };
  94009. this._onPointerMoveHandlerRef = function (evt) {
  94010. _this._onPointerMove(evt);
  94011. };
  94012. this._onPointerUpHandlerRef = function (evt) {
  94013. _this._onPointerUp(evt);
  94014. };
  94015. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94016. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94017. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94018. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94019. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94020. evt.preventDefault(); // Disables system menu
  94021. }, false);
  94022. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94023. }
  94024. /**
  94025. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94026. * @param newJoystickSensibility defines the new sensibility
  94027. */
  94028. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94029. this._joystickSensibility = newJoystickSensibility;
  94030. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94031. };
  94032. VirtualJoystick.prototype._onPointerDown = function (e) {
  94033. var positionOnScreenCondition;
  94034. e.preventDefault();
  94035. if (this._leftJoystick === true) {
  94036. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94037. }
  94038. else {
  94039. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94040. }
  94041. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94042. // First contact will be dedicated to the virtual joystick
  94043. this._joystickPointerID = e.pointerId;
  94044. this._joystickPointerStartPos.x = e.clientX;
  94045. this._joystickPointerStartPos.y = e.clientY;
  94046. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94047. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94048. this._deltaJoystickVector.x = 0;
  94049. this._deltaJoystickVector.y = 0;
  94050. this.pressed = true;
  94051. this._touches.add(e.pointerId.toString(), e);
  94052. }
  94053. else {
  94054. // You can only trigger the action buttons with a joystick declared
  94055. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94056. this._action();
  94057. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94058. }
  94059. }
  94060. };
  94061. VirtualJoystick.prototype._onPointerMove = function (e) {
  94062. // If the current pointer is the one associated to the joystick (first touch contact)
  94063. if (this._joystickPointerID == e.pointerId) {
  94064. this._joystickPointerPos.x = e.clientX;
  94065. this._joystickPointerPos.y = e.clientY;
  94066. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94067. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94068. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94069. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94070. switch (this._axisTargetedByLeftAndRight) {
  94071. case JoystickAxis.X:
  94072. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94073. break;
  94074. case JoystickAxis.Y:
  94075. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94076. break;
  94077. case JoystickAxis.Z:
  94078. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94079. break;
  94080. }
  94081. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94082. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94083. switch (this._axisTargetedByUpAndDown) {
  94084. case JoystickAxis.X:
  94085. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94086. break;
  94087. case JoystickAxis.Y:
  94088. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94089. break;
  94090. case JoystickAxis.Z:
  94091. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94092. break;
  94093. }
  94094. }
  94095. else {
  94096. var data = this._touches.get(e.pointerId.toString());
  94097. if (data) {
  94098. data.x = e.clientX;
  94099. data.y = e.clientY;
  94100. }
  94101. }
  94102. };
  94103. VirtualJoystick.prototype._onPointerUp = function (e) {
  94104. if (this._joystickPointerID == e.pointerId) {
  94105. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94106. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94107. this._joystickPointerID = -1;
  94108. this.pressed = false;
  94109. }
  94110. else {
  94111. var touch = this._touches.get(e.pointerId.toString());
  94112. if (touch) {
  94113. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94114. }
  94115. }
  94116. this._deltaJoystickVector.x = 0;
  94117. this._deltaJoystickVector.y = 0;
  94118. this._touches.remove(e.pointerId.toString());
  94119. };
  94120. /**
  94121. * Change the color of the virtual joystick
  94122. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94123. */
  94124. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94125. this._joystickColor = newColor;
  94126. };
  94127. /**
  94128. * Defines a callback to call when the joystick is touched
  94129. * @param action defines the callback
  94130. */
  94131. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94132. this._action = action;
  94133. };
  94134. /**
  94135. * Defines which axis you'd like to control for left & right
  94136. * @param axis defines the axis to use
  94137. */
  94138. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94139. switch (axis) {
  94140. case JoystickAxis.X:
  94141. case JoystickAxis.Y:
  94142. case JoystickAxis.Z:
  94143. this._axisTargetedByLeftAndRight = axis;
  94144. break;
  94145. default:
  94146. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94147. break;
  94148. }
  94149. };
  94150. /**
  94151. * Defines which axis you'd like to control for up & down
  94152. * @param axis defines the axis to use
  94153. */
  94154. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94155. switch (axis) {
  94156. case JoystickAxis.X:
  94157. case JoystickAxis.Y:
  94158. case JoystickAxis.Z:
  94159. this._axisTargetedByUpAndDown = axis;
  94160. break;
  94161. default:
  94162. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94163. break;
  94164. }
  94165. };
  94166. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94167. var _this = this;
  94168. if (this.pressed) {
  94169. this._touches.forEach(function (key, touch) {
  94170. if (touch.pointerId === _this._joystickPointerID) {
  94171. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94172. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94173. VirtualJoystick.vjCanvasContext.beginPath();
  94174. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94175. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94176. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94177. VirtualJoystick.vjCanvasContext.stroke();
  94178. VirtualJoystick.vjCanvasContext.closePath();
  94179. VirtualJoystick.vjCanvasContext.beginPath();
  94180. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94181. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94182. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94183. VirtualJoystick.vjCanvasContext.stroke();
  94184. VirtualJoystick.vjCanvasContext.closePath();
  94185. VirtualJoystick.vjCanvasContext.beginPath();
  94186. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94187. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94188. VirtualJoystick.vjCanvasContext.stroke();
  94189. VirtualJoystick.vjCanvasContext.closePath();
  94190. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94191. }
  94192. else {
  94193. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94194. VirtualJoystick.vjCanvasContext.beginPath();
  94195. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94196. VirtualJoystick.vjCanvasContext.beginPath();
  94197. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94198. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94199. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94200. VirtualJoystick.vjCanvasContext.stroke();
  94201. VirtualJoystick.vjCanvasContext.closePath();
  94202. touch.prevX = touch.x;
  94203. touch.prevY = touch.y;
  94204. }
  94205. ;
  94206. });
  94207. }
  94208. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94209. };
  94210. /**
  94211. * Release internal HTML canvas
  94212. */
  94213. VirtualJoystick.prototype.releaseCanvas = function () {
  94214. if (VirtualJoystick.vjCanvas) {
  94215. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94216. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94217. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94218. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94219. window.removeEventListener("resize", this._onResize);
  94220. document.body.removeChild(VirtualJoystick.vjCanvas);
  94221. VirtualJoystick.vjCanvas = null;
  94222. }
  94223. };
  94224. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94225. VirtualJoystick._globalJoystickIndex = 0;
  94226. return VirtualJoystick;
  94227. }());
  94228. BABYLON.VirtualJoystick = VirtualJoystick;
  94229. })(BABYLON || (BABYLON = {}));
  94230. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94231. var BABYLON;
  94232. (function (BABYLON) {
  94233. // We're mainly based on the logic defined into the FreeCamera code
  94234. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94235. __extends(VirtualJoysticksCamera, _super);
  94236. function VirtualJoysticksCamera(name, position, scene) {
  94237. var _this = _super.call(this, name, position, scene) || this;
  94238. _this.inputs.addVirtualJoystick();
  94239. return _this;
  94240. }
  94241. VirtualJoysticksCamera.prototype.getClassName = function () {
  94242. return "VirtualJoysticksCamera";
  94243. };
  94244. return VirtualJoysticksCamera;
  94245. }(BABYLON.FreeCamera));
  94246. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94247. })(BABYLON || (BABYLON = {}));
  94248. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94249. var BABYLON;
  94250. (function (BABYLON) {
  94251. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94252. function FreeCameraVirtualJoystickInput() {
  94253. }
  94254. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94255. return this._leftjoystick;
  94256. };
  94257. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94258. return this._rightjoystick;
  94259. };
  94260. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94261. if (this._leftjoystick) {
  94262. var camera = this.camera;
  94263. var speed = camera._computeLocalCameraSpeed() * 50;
  94264. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94265. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94266. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94267. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94268. if (!this._leftjoystick.pressed) {
  94269. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94270. }
  94271. if (!this._rightjoystick.pressed) {
  94272. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94273. }
  94274. }
  94275. };
  94276. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94277. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94278. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94279. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94280. this._leftjoystick.setJoystickSensibility(0.15);
  94281. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94282. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94283. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94284. this._rightjoystick.reverseUpDown = true;
  94285. this._rightjoystick.setJoystickSensibility(0.05);
  94286. this._rightjoystick.setJoystickColor("yellow");
  94287. };
  94288. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94289. this._leftjoystick.releaseCanvas();
  94290. this._rightjoystick.releaseCanvas();
  94291. };
  94292. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94293. return "FreeCameraVirtualJoystickInput";
  94294. };
  94295. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94296. return "virtualJoystick";
  94297. };
  94298. return FreeCameraVirtualJoystickInput;
  94299. }());
  94300. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94301. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94302. })(BABYLON || (BABYLON = {}));
  94303. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94304. var BABYLON;
  94305. (function (BABYLON) {
  94306. var SimplificationSettings = /** @class */ (function () {
  94307. function SimplificationSettings(quality, distance, optimizeMesh) {
  94308. this.quality = quality;
  94309. this.distance = distance;
  94310. this.optimizeMesh = optimizeMesh;
  94311. }
  94312. return SimplificationSettings;
  94313. }());
  94314. BABYLON.SimplificationSettings = SimplificationSettings;
  94315. var SimplificationQueue = /** @class */ (function () {
  94316. function SimplificationQueue() {
  94317. this.running = false;
  94318. this._simplificationArray = [];
  94319. }
  94320. SimplificationQueue.prototype.addTask = function (task) {
  94321. this._simplificationArray.push(task);
  94322. };
  94323. SimplificationQueue.prototype.executeNext = function () {
  94324. var task = this._simplificationArray.pop();
  94325. if (task) {
  94326. this.running = true;
  94327. this.runSimplification(task);
  94328. }
  94329. else {
  94330. this.running = false;
  94331. }
  94332. };
  94333. SimplificationQueue.prototype.runSimplification = function (task) {
  94334. var _this = this;
  94335. if (task.parallelProcessing) {
  94336. //parallel simplifier
  94337. task.settings.forEach(function (setting) {
  94338. var simplifier = _this.getSimplifier(task);
  94339. simplifier.simplify(setting, function (newMesh) {
  94340. task.mesh.addLODLevel(setting.distance, newMesh);
  94341. newMesh.isVisible = true;
  94342. //check if it is the last
  94343. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94344. //all done, run the success callback.
  94345. task.successCallback();
  94346. }
  94347. _this.executeNext();
  94348. });
  94349. });
  94350. }
  94351. else {
  94352. //single simplifier.
  94353. var simplifier = this.getSimplifier(task);
  94354. var runDecimation = function (setting, callback) {
  94355. simplifier.simplify(setting, function (newMesh) {
  94356. task.mesh.addLODLevel(setting.distance, newMesh);
  94357. newMesh.isVisible = true;
  94358. //run the next quality level
  94359. callback();
  94360. });
  94361. };
  94362. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94363. runDecimation(task.settings[loop.index], function () {
  94364. loop.executeNext();
  94365. });
  94366. }, function () {
  94367. //execution ended, run the success callback.
  94368. if (task.successCallback) {
  94369. task.successCallback();
  94370. }
  94371. _this.executeNext();
  94372. });
  94373. }
  94374. };
  94375. SimplificationQueue.prototype.getSimplifier = function (task) {
  94376. switch (task.simplificationType) {
  94377. case SimplificationType.QUADRATIC:
  94378. default:
  94379. return new QuadraticErrorSimplification(task.mesh);
  94380. }
  94381. };
  94382. return SimplificationQueue;
  94383. }());
  94384. BABYLON.SimplificationQueue = SimplificationQueue;
  94385. /**
  94386. * The implemented types of simplification
  94387. * At the moment only Quadratic Error Decimation is implemented
  94388. */
  94389. var SimplificationType;
  94390. (function (SimplificationType) {
  94391. /** Quadratic error decimation */
  94392. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94393. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94394. var DecimationTriangle = /** @class */ (function () {
  94395. function DecimationTriangle(vertices) {
  94396. this.vertices = vertices;
  94397. this.error = new Array(4);
  94398. this.deleted = false;
  94399. this.isDirty = false;
  94400. this.deletePending = false;
  94401. this.borderFactor = 0;
  94402. }
  94403. return DecimationTriangle;
  94404. }());
  94405. BABYLON.DecimationTriangle = DecimationTriangle;
  94406. var DecimationVertex = /** @class */ (function () {
  94407. function DecimationVertex(position, id) {
  94408. this.position = position;
  94409. this.id = id;
  94410. this.isBorder = true;
  94411. this.q = new QuadraticMatrix();
  94412. this.triangleCount = 0;
  94413. this.triangleStart = 0;
  94414. this.originalOffsets = [];
  94415. }
  94416. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94417. this.position.copyFrom(newPosition);
  94418. };
  94419. return DecimationVertex;
  94420. }());
  94421. BABYLON.DecimationVertex = DecimationVertex;
  94422. var QuadraticMatrix = /** @class */ (function () {
  94423. function QuadraticMatrix(data) {
  94424. this.data = new Array(10);
  94425. for (var i = 0; i < 10; ++i) {
  94426. if (data && data[i]) {
  94427. this.data[i] = data[i];
  94428. }
  94429. else {
  94430. this.data[i] = 0;
  94431. }
  94432. }
  94433. }
  94434. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94435. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94436. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94437. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94438. return det;
  94439. };
  94440. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94441. for (var i = 0; i < 10; ++i) {
  94442. this.data[i] += matrix.data[i];
  94443. }
  94444. };
  94445. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94446. for (var i = 0; i < 10; ++i) {
  94447. this.data[i] += data[i];
  94448. }
  94449. };
  94450. QuadraticMatrix.prototype.add = function (matrix) {
  94451. var m = new QuadraticMatrix();
  94452. for (var i = 0; i < 10; ++i) {
  94453. m.data[i] = this.data[i] + matrix.data[i];
  94454. }
  94455. return m;
  94456. };
  94457. QuadraticMatrix.FromData = function (a, b, c, d) {
  94458. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94459. };
  94460. //returning an array to avoid garbage collection
  94461. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94462. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94463. };
  94464. return QuadraticMatrix;
  94465. }());
  94466. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94467. var Reference = /** @class */ (function () {
  94468. function Reference(vertexId, triangleId) {
  94469. this.vertexId = vertexId;
  94470. this.triangleId = triangleId;
  94471. }
  94472. return Reference;
  94473. }());
  94474. BABYLON.Reference = Reference;
  94475. /**
  94476. * An implementation of the Quadratic Error simplification algorithm.
  94477. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94478. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94479. * @author RaananW
  94480. */
  94481. var QuadraticErrorSimplification = /** @class */ (function () {
  94482. function QuadraticErrorSimplification(_mesh) {
  94483. this._mesh = _mesh;
  94484. this.syncIterations = 5000;
  94485. this.aggressiveness = 7;
  94486. this.decimationIterations = 100;
  94487. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94488. }
  94489. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94490. var _this = this;
  94491. this.initDecimatedMesh();
  94492. //iterating through the submeshes array, one after the other.
  94493. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94494. _this.initWithMesh(loop.index, function () {
  94495. _this.runDecimation(settings, loop.index, function () {
  94496. loop.executeNext();
  94497. });
  94498. }, settings.optimizeMesh);
  94499. }, function () {
  94500. setTimeout(function () {
  94501. successCallback(_this._reconstructedMesh);
  94502. }, 0);
  94503. });
  94504. };
  94505. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94506. var _this = this;
  94507. var targetCount = ~~(this.triangles.length * settings.quality);
  94508. var deletedTriangles = 0;
  94509. var triangleCount = this.triangles.length;
  94510. var iterationFunction = function (iteration, callback) {
  94511. setTimeout(function () {
  94512. if (iteration % 5 === 0) {
  94513. _this.updateMesh(iteration === 0);
  94514. }
  94515. for (var i = 0; i < _this.triangles.length; ++i) {
  94516. _this.triangles[i].isDirty = false;
  94517. }
  94518. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94519. var trianglesIterator = function (i) {
  94520. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94521. var t = _this.triangles[tIdx];
  94522. if (!t)
  94523. return;
  94524. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94525. return;
  94526. }
  94527. for (var j = 0; j < 3; ++j) {
  94528. if (t.error[j] < threshold) {
  94529. var deleted0 = [];
  94530. var deleted1 = [];
  94531. var v0 = t.vertices[j];
  94532. var v1 = t.vertices[(j + 1) % 3];
  94533. if (v0.isBorder || v1.isBorder)
  94534. continue;
  94535. var p = BABYLON.Vector3.Zero();
  94536. var n = BABYLON.Vector3.Zero();
  94537. var uv = BABYLON.Vector2.Zero();
  94538. var color = new BABYLON.Color4(0, 0, 0, 1);
  94539. _this.calculateError(v0, v1, p, n, uv, color);
  94540. var delTr = new Array();
  94541. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94542. continue;
  94543. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94544. continue;
  94545. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94546. continue;
  94547. var uniqueArray = new Array();
  94548. delTr.forEach(function (deletedT) {
  94549. if (uniqueArray.indexOf(deletedT) === -1) {
  94550. deletedT.deletePending = true;
  94551. uniqueArray.push(deletedT);
  94552. }
  94553. });
  94554. if (uniqueArray.length % 2 !== 0) {
  94555. continue;
  94556. }
  94557. v0.q = v1.q.add(v0.q);
  94558. v0.updatePosition(p);
  94559. var tStart = _this.references.length;
  94560. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94561. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94562. var tCount = _this.references.length - tStart;
  94563. if (tCount <= v0.triangleCount) {
  94564. if (tCount) {
  94565. for (var c = 0; c < tCount; c++) {
  94566. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94567. }
  94568. }
  94569. }
  94570. else {
  94571. v0.triangleStart = tStart;
  94572. }
  94573. v0.triangleCount = tCount;
  94574. break;
  94575. }
  94576. }
  94577. };
  94578. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94579. }, 0);
  94580. };
  94581. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94582. if (triangleCount - deletedTriangles <= targetCount)
  94583. loop.breakLoop();
  94584. else {
  94585. iterationFunction(loop.index, function () {
  94586. loop.executeNext();
  94587. });
  94588. }
  94589. }, function () {
  94590. setTimeout(function () {
  94591. //reconstruct this part of the mesh
  94592. _this.reconstructMesh(submeshIndex);
  94593. successCallback();
  94594. }, 0);
  94595. });
  94596. };
  94597. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94598. var _this = this;
  94599. this.vertices = [];
  94600. this.triangles = [];
  94601. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94602. var indices = this._mesh.getIndices();
  94603. var submesh = this._mesh.subMeshes[submeshIndex];
  94604. var findInVertices = function (positionToSearch) {
  94605. if (optimizeMesh) {
  94606. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94607. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94608. return _this.vertices[ii];
  94609. }
  94610. }
  94611. }
  94612. return null;
  94613. };
  94614. var vertexReferences = [];
  94615. var vertexInit = function (i) {
  94616. if (!positionData) {
  94617. return;
  94618. }
  94619. var offset = i + submesh.verticesStart;
  94620. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94621. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94622. vertex.originalOffsets.push(offset);
  94623. if (vertex.id === _this.vertices.length) {
  94624. _this.vertices.push(vertex);
  94625. }
  94626. vertexReferences.push(vertex.id);
  94627. };
  94628. //var totalVertices = mesh.getTotalVertices();
  94629. var totalVertices = submesh.verticesCount;
  94630. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94631. var indicesInit = function (i) {
  94632. if (!indices) {
  94633. return;
  94634. }
  94635. var offset = (submesh.indexStart / 3) + i;
  94636. var pos = (offset * 3);
  94637. var i0 = indices[pos + 0];
  94638. var i1 = indices[pos + 1];
  94639. var i2 = indices[pos + 2];
  94640. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94641. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94642. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94643. var triangle = new DecimationTriangle([v0, v1, v2]);
  94644. triangle.originalOffset = pos;
  94645. _this.triangles.push(triangle);
  94646. };
  94647. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94648. _this.init(callback);
  94649. });
  94650. });
  94651. };
  94652. QuadraticErrorSimplification.prototype.init = function (callback) {
  94653. var _this = this;
  94654. var triangleInit1 = function (i) {
  94655. var t = _this.triangles[i];
  94656. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94657. for (var j = 0; j < 3; j++) {
  94658. 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))));
  94659. }
  94660. };
  94661. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94662. var triangleInit2 = function (i) {
  94663. var t = _this.triangles[i];
  94664. for (var j = 0; j < 3; ++j) {
  94665. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94666. }
  94667. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94668. };
  94669. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94670. callback();
  94671. });
  94672. });
  94673. };
  94674. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94675. var newTriangles = [];
  94676. var i;
  94677. for (i = 0; i < this.vertices.length; ++i) {
  94678. this.vertices[i].triangleCount = 0;
  94679. }
  94680. var t;
  94681. var j;
  94682. for (i = 0; i < this.triangles.length; ++i) {
  94683. if (!this.triangles[i].deleted) {
  94684. t = this.triangles[i];
  94685. for (j = 0; j < 3; ++j) {
  94686. t.vertices[j].triangleCount = 1;
  94687. }
  94688. newTriangles.push(t);
  94689. }
  94690. }
  94691. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94692. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94693. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94694. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94695. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94696. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94697. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94698. var vertexCount = 0;
  94699. for (i = 0; i < this.vertices.length; ++i) {
  94700. var vertex = this.vertices[i];
  94701. vertex.id = vertexCount;
  94702. if (vertex.triangleCount) {
  94703. vertex.originalOffsets.forEach(function (originalOffset) {
  94704. if (!normalData) {
  94705. return;
  94706. }
  94707. newPositionData.push(vertex.position.x);
  94708. newPositionData.push(vertex.position.y);
  94709. newPositionData.push(vertex.position.z);
  94710. newNormalData.push(normalData[originalOffset * 3]);
  94711. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94712. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94713. if (uvs && uvs.length) {
  94714. newUVsData.push(uvs[(originalOffset * 2)]);
  94715. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94716. }
  94717. else if (colorsData && colorsData.length) {
  94718. newColorsData.push(colorsData[(originalOffset * 4)]);
  94719. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94720. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94721. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94722. }
  94723. ++vertexCount;
  94724. });
  94725. }
  94726. }
  94727. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94728. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94729. var submeshesArray = this._reconstructedMesh.subMeshes;
  94730. this._reconstructedMesh.subMeshes = [];
  94731. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94732. var originalIndices = this._mesh.getIndices();
  94733. for (i = 0; i < newTriangles.length; ++i) {
  94734. t = newTriangles[i]; //now get the new referencing point for each vertex
  94735. [0, 1, 2].forEach(function (idx) {
  94736. var id = originalIndices[t.originalOffset + idx];
  94737. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94738. if (offset < 0)
  94739. offset = 0;
  94740. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94741. });
  94742. }
  94743. //overwriting the old vertex buffers and indices.
  94744. this._reconstructedMesh.setIndices(newIndicesArray);
  94745. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94746. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94747. if (newUVsData.length > 0)
  94748. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94749. if (newColorsData.length > 0)
  94750. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94751. //create submesh
  94752. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94753. if (submeshIndex > 0) {
  94754. this._reconstructedMesh.subMeshes = [];
  94755. submeshesArray.forEach(function (submesh) {
  94756. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94757. });
  94758. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94759. }
  94760. };
  94761. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94762. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94763. this._reconstructedMesh.material = this._mesh.material;
  94764. this._reconstructedMesh.parent = this._mesh.parent;
  94765. this._reconstructedMesh.isVisible = false;
  94766. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94767. };
  94768. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94769. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94770. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94771. if (t.deleted)
  94772. continue;
  94773. var s = this.references[vertex1.triangleStart + i].vertexId;
  94774. var v1 = t.vertices[(s + 1) % 3];
  94775. var v2 = t.vertices[(s + 2) % 3];
  94776. if ((v1 === vertex2 || v2 === vertex2)) {
  94777. deletedArray[i] = true;
  94778. delTr.push(t);
  94779. continue;
  94780. }
  94781. var d1 = v1.position.subtract(point);
  94782. d1 = d1.normalize();
  94783. var d2 = v2.position.subtract(point);
  94784. d2 = d2.normalize();
  94785. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94786. return true;
  94787. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94788. deletedArray[i] = false;
  94789. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94790. return true;
  94791. }
  94792. return false;
  94793. };
  94794. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94795. var newDeleted = deletedTriangles;
  94796. for (var i = 0; i < vertex.triangleCount; ++i) {
  94797. var ref = this.references[vertex.triangleStart + i];
  94798. var t = this.triangles[ref.triangleId];
  94799. if (t.deleted)
  94800. continue;
  94801. if (deletedArray[i] && t.deletePending) {
  94802. t.deleted = true;
  94803. newDeleted++;
  94804. continue;
  94805. }
  94806. t.vertices[ref.vertexId] = origVertex;
  94807. t.isDirty = true;
  94808. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94809. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94810. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94811. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94812. this.references.push(ref);
  94813. }
  94814. return newDeleted;
  94815. };
  94816. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94817. for (var i = 0; i < this.vertices.length; ++i) {
  94818. var vCount = [];
  94819. var vId = [];
  94820. var v = this.vertices[i];
  94821. var j;
  94822. for (j = 0; j < v.triangleCount; ++j) {
  94823. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94824. for (var ii = 0; ii < 3; ii++) {
  94825. var ofs = 0;
  94826. var vv = triangle.vertices[ii];
  94827. while (ofs < vCount.length) {
  94828. if (vId[ofs] === vv.id)
  94829. break;
  94830. ++ofs;
  94831. }
  94832. if (ofs === vCount.length) {
  94833. vCount.push(1);
  94834. vId.push(vv.id);
  94835. }
  94836. else {
  94837. vCount[ofs]++;
  94838. }
  94839. }
  94840. }
  94841. for (j = 0; j < vCount.length; ++j) {
  94842. if (vCount[j] === 1) {
  94843. this.vertices[vId[j]].isBorder = true;
  94844. }
  94845. else {
  94846. this.vertices[vId[j]].isBorder = false;
  94847. }
  94848. }
  94849. }
  94850. };
  94851. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94852. if (identifyBorders === void 0) { identifyBorders = false; }
  94853. var i;
  94854. if (!identifyBorders) {
  94855. var newTrianglesVector = [];
  94856. for (i = 0; i < this.triangles.length; ++i) {
  94857. if (!this.triangles[i].deleted) {
  94858. newTrianglesVector.push(this.triangles[i]);
  94859. }
  94860. }
  94861. this.triangles = newTrianglesVector;
  94862. }
  94863. for (i = 0; i < this.vertices.length; ++i) {
  94864. this.vertices[i].triangleCount = 0;
  94865. this.vertices[i].triangleStart = 0;
  94866. }
  94867. var t;
  94868. var j;
  94869. var v;
  94870. for (i = 0; i < this.triangles.length; ++i) {
  94871. t = this.triangles[i];
  94872. for (j = 0; j < 3; ++j) {
  94873. v = t.vertices[j];
  94874. v.triangleCount++;
  94875. }
  94876. }
  94877. var tStart = 0;
  94878. for (i = 0; i < this.vertices.length; ++i) {
  94879. this.vertices[i].triangleStart = tStart;
  94880. tStart += this.vertices[i].triangleCount;
  94881. this.vertices[i].triangleCount = 0;
  94882. }
  94883. var newReferences = new Array(this.triangles.length * 3);
  94884. for (i = 0; i < this.triangles.length; ++i) {
  94885. t = this.triangles[i];
  94886. for (j = 0; j < 3; ++j) {
  94887. v = t.vertices[j];
  94888. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94889. v.triangleCount++;
  94890. }
  94891. }
  94892. this.references = newReferences;
  94893. if (identifyBorders) {
  94894. this.identifyBorder();
  94895. }
  94896. };
  94897. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94898. var x = point.x;
  94899. var y = point.y;
  94900. var z = point.z;
  94901. 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
  94902. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94903. };
  94904. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94905. var q = vertex1.q.add(vertex2.q);
  94906. var border = vertex1.isBorder && vertex2.isBorder;
  94907. var error = 0;
  94908. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94909. if (qDet !== 0 && !border) {
  94910. if (!pointResult) {
  94911. pointResult = BABYLON.Vector3.Zero();
  94912. }
  94913. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94914. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94915. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94916. error = this.vertexError(q, pointResult);
  94917. }
  94918. else {
  94919. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94920. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94921. var error1 = this.vertexError(q, vertex1.position);
  94922. var error2 = this.vertexError(q, vertex2.position);
  94923. var error3 = this.vertexError(q, p3);
  94924. error = Math.min(error1, error2, error3);
  94925. if (error === error1) {
  94926. if (pointResult) {
  94927. pointResult.copyFrom(vertex1.position);
  94928. }
  94929. }
  94930. else if (error === error2) {
  94931. if (pointResult) {
  94932. pointResult.copyFrom(vertex2.position);
  94933. }
  94934. }
  94935. else {
  94936. if (pointResult) {
  94937. pointResult.copyFrom(p3);
  94938. }
  94939. }
  94940. }
  94941. return error;
  94942. };
  94943. return QuadraticErrorSimplification;
  94944. }());
  94945. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94946. })(BABYLON || (BABYLON = {}));
  94947. //# sourceMappingURL=babylon.meshSimplification.js.map
  94948. var BABYLON;
  94949. (function (BABYLON) {
  94950. var MeshLODLevel = /** @class */ (function () {
  94951. function MeshLODLevel(distance, mesh) {
  94952. this.distance = distance;
  94953. this.mesh = mesh;
  94954. }
  94955. return MeshLODLevel;
  94956. }());
  94957. BABYLON.MeshLODLevel = MeshLODLevel;
  94958. })(BABYLON || (BABYLON = {}));
  94959. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94960. var BABYLON;
  94961. (function (BABYLON) {
  94962. /**
  94963. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94964. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94965. */
  94966. var SceneOptimization = /** @class */ (function () {
  94967. /**
  94968. * Creates the SceneOptimization object
  94969. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94970. * @param desc defines the description associated with the optimization
  94971. */
  94972. function SceneOptimization(
  94973. /**
  94974. * Defines the priority of this optimization (0 by default which means first in the list)
  94975. */
  94976. priority) {
  94977. if (priority === void 0) { priority = 0; }
  94978. this.priority = priority;
  94979. }
  94980. /**
  94981. * Gets a string describing the action executed by the current optimization
  94982. * @returns description string
  94983. */
  94984. SceneOptimization.prototype.getDescription = function () {
  94985. return "";
  94986. };
  94987. /**
  94988. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94989. * @param scene defines the current scene where to apply this optimization
  94990. * @param optimizer defines the current optimizer
  94991. * @returns true if everything that can be done was applied
  94992. */
  94993. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94994. return true;
  94995. };
  94996. ;
  94997. return SceneOptimization;
  94998. }());
  94999. BABYLON.SceneOptimization = SceneOptimization;
  95000. /**
  95001. * Defines an optimization used to reduce the size of render target textures
  95002. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95003. */
  95004. var TextureOptimization = /** @class */ (function (_super) {
  95005. __extends(TextureOptimization, _super);
  95006. /**
  95007. * Creates the TextureOptimization object
  95008. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95009. * @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
  95010. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95011. */
  95012. function TextureOptimization(
  95013. /**
  95014. * Defines the priority of this optimization (0 by default which means first in the list)
  95015. */
  95016. priority,
  95017. /**
  95018. * 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
  95019. */
  95020. maximumSize,
  95021. /**
  95022. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95023. */
  95024. step) {
  95025. if (priority === void 0) { priority = 0; }
  95026. if (maximumSize === void 0) { maximumSize = 1024; }
  95027. if (step === void 0) { step = 0.5; }
  95028. var _this = _super.call(this, priority) || this;
  95029. _this.priority = priority;
  95030. _this.maximumSize = maximumSize;
  95031. _this.step = step;
  95032. return _this;
  95033. }
  95034. /**
  95035. * Gets a string describing the action executed by the current optimization
  95036. * @returns description string
  95037. */
  95038. TextureOptimization.prototype.getDescription = function () {
  95039. return "Reducing render target texture size to " + this.maximumSize;
  95040. };
  95041. /**
  95042. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95043. * @param scene defines the current scene where to apply this optimization
  95044. * @param optimizer defines the current optimizer
  95045. * @returns true if everything that can be done was applied
  95046. */
  95047. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95048. var allDone = true;
  95049. for (var index = 0; index < scene.textures.length; index++) {
  95050. var texture = scene.textures[index];
  95051. if (!texture.canRescale || texture.getContext) {
  95052. continue;
  95053. }
  95054. var currentSize = texture.getSize();
  95055. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95056. if (maxDimension > this.maximumSize) {
  95057. texture.scale(this.step);
  95058. allDone = false;
  95059. }
  95060. }
  95061. return allDone;
  95062. };
  95063. return TextureOptimization;
  95064. }(SceneOptimization));
  95065. BABYLON.TextureOptimization = TextureOptimization;
  95066. /**
  95067. * Defines an optimization used to increase or decrease the rendering resolution
  95068. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95069. */
  95070. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95071. __extends(HardwareScalingOptimization, _super);
  95072. /**
  95073. * Creates the HardwareScalingOptimization object
  95074. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95075. * @param maximumScale defines the maximum scale to use (2 by default)
  95076. * @param step defines the step to use between two passes (0.5 by default)
  95077. */
  95078. function HardwareScalingOptimization(
  95079. /**
  95080. * Defines the priority of this optimization (0 by default which means first in the list)
  95081. */
  95082. priority,
  95083. /**
  95084. * Defines the maximum scale to use (2 by default)
  95085. */
  95086. maximumScale,
  95087. /**
  95088. * Defines the step to use between two passes (0.5 by default)
  95089. */
  95090. step) {
  95091. if (priority === void 0) { priority = 0; }
  95092. if (maximumScale === void 0) { maximumScale = 2; }
  95093. if (step === void 0) { step = 0.25; }
  95094. var _this = _super.call(this, priority) || this;
  95095. _this.priority = priority;
  95096. _this.maximumScale = maximumScale;
  95097. _this.step = step;
  95098. _this._currentScale = -1;
  95099. _this._directionOffset = 1;
  95100. return _this;
  95101. }
  95102. /**
  95103. * Gets a string describing the action executed by the current optimization
  95104. * @return description string
  95105. */
  95106. HardwareScalingOptimization.prototype.getDescription = function () {
  95107. return "Setting hardware scaling level to " + this._currentScale;
  95108. };
  95109. /**
  95110. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95111. * @param scene defines the current scene where to apply this optimization
  95112. * @param optimizer defines the current optimizer
  95113. * @returns true if everything that can be done was applied
  95114. */
  95115. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95116. if (this._currentScale === -1) {
  95117. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95118. if (this._currentScale > this.maximumScale) {
  95119. this._directionOffset = -1;
  95120. }
  95121. }
  95122. this._currentScale += this._directionOffset * this.step;
  95123. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95124. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95125. };
  95126. ;
  95127. return HardwareScalingOptimization;
  95128. }(SceneOptimization));
  95129. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95130. /**
  95131. * Defines an optimization used to remove shadows
  95132. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95133. */
  95134. var ShadowsOptimization = /** @class */ (function (_super) {
  95135. __extends(ShadowsOptimization, _super);
  95136. function ShadowsOptimization() {
  95137. return _super !== null && _super.apply(this, arguments) || this;
  95138. }
  95139. /**
  95140. * Gets a string describing the action executed by the current optimization
  95141. * @return description string
  95142. */
  95143. ShadowsOptimization.prototype.getDescription = function () {
  95144. return "Turning shadows on/off";
  95145. };
  95146. /**
  95147. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95148. * @param scene defines the current scene where to apply this optimization
  95149. * @param optimizer defines the current optimizer
  95150. * @returns true if everything that can be done was applied
  95151. */
  95152. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95153. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95154. return true;
  95155. };
  95156. ;
  95157. return ShadowsOptimization;
  95158. }(SceneOptimization));
  95159. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95160. /**
  95161. * Defines an optimization used to turn post-processes off
  95162. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95163. */
  95164. var PostProcessesOptimization = /** @class */ (function (_super) {
  95165. __extends(PostProcessesOptimization, _super);
  95166. function PostProcessesOptimization() {
  95167. return _super !== null && _super.apply(this, arguments) || this;
  95168. }
  95169. /**
  95170. * Gets a string describing the action executed by the current optimization
  95171. * @return description string
  95172. */
  95173. PostProcessesOptimization.prototype.getDescription = function () {
  95174. return "Turning post-processes on/off";
  95175. };
  95176. /**
  95177. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95178. * @param scene defines the current scene where to apply this optimization
  95179. * @param optimizer defines the current optimizer
  95180. * @returns true if everything that can be done was applied
  95181. */
  95182. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95183. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95184. return true;
  95185. };
  95186. ;
  95187. return PostProcessesOptimization;
  95188. }(SceneOptimization));
  95189. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95190. /**
  95191. * Defines an optimization used to turn lens flares off
  95192. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95193. */
  95194. var LensFlaresOptimization = /** @class */ (function (_super) {
  95195. __extends(LensFlaresOptimization, _super);
  95196. function LensFlaresOptimization() {
  95197. return _super !== null && _super.apply(this, arguments) || this;
  95198. }
  95199. /**
  95200. * Gets a string describing the action executed by the current optimization
  95201. * @return description string
  95202. */
  95203. LensFlaresOptimization.prototype.getDescription = function () {
  95204. return "Turning lens flares on/off";
  95205. };
  95206. /**
  95207. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95208. * @param scene defines the current scene where to apply this optimization
  95209. * @param optimizer defines the current optimizer
  95210. * @returns true if everything that can be done was applied
  95211. */
  95212. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95213. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95214. return true;
  95215. };
  95216. ;
  95217. return LensFlaresOptimization;
  95218. }(SceneOptimization));
  95219. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95220. /**
  95221. * Defines an optimization based on user defined callback.
  95222. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95223. */
  95224. var CustomOptimization = /** @class */ (function (_super) {
  95225. __extends(CustomOptimization, _super);
  95226. function CustomOptimization() {
  95227. return _super !== null && _super.apply(this, arguments) || this;
  95228. }
  95229. /**
  95230. * Gets a string describing the action executed by the current optimization
  95231. * @returns description string
  95232. */
  95233. CustomOptimization.prototype.getDescription = function () {
  95234. if (this.onGetDescription) {
  95235. return this.onGetDescription();
  95236. }
  95237. return "Running user defined callback";
  95238. };
  95239. /**
  95240. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95241. * @param scene defines the current scene where to apply this optimization
  95242. * @param optimizer defines the current optimizer
  95243. * @returns true if everything that can be done was applied
  95244. */
  95245. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95246. if (this.onApply) {
  95247. return this.onApply(scene, optimizer);
  95248. }
  95249. return true;
  95250. };
  95251. ;
  95252. return CustomOptimization;
  95253. }(SceneOptimization));
  95254. BABYLON.CustomOptimization = CustomOptimization;
  95255. /**
  95256. * Defines an optimization used to turn particles off
  95257. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95258. */
  95259. var ParticlesOptimization = /** @class */ (function (_super) {
  95260. __extends(ParticlesOptimization, _super);
  95261. function ParticlesOptimization() {
  95262. return _super !== null && _super.apply(this, arguments) || this;
  95263. }
  95264. /**
  95265. * Gets a string describing the action executed by the current optimization
  95266. * @return description string
  95267. */
  95268. ParticlesOptimization.prototype.getDescription = function () {
  95269. return "Turning particles on/off";
  95270. };
  95271. /**
  95272. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95273. * @param scene defines the current scene where to apply this optimization
  95274. * @param optimizer defines the current optimizer
  95275. * @returns true if everything that can be done was applied
  95276. */
  95277. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95278. scene.particlesEnabled = optimizer.isInImprovementMode;
  95279. return true;
  95280. };
  95281. ;
  95282. return ParticlesOptimization;
  95283. }(SceneOptimization));
  95284. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95285. /**
  95286. * Defines an optimization used to turn render targets off
  95287. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95288. */
  95289. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95290. __extends(RenderTargetsOptimization, _super);
  95291. function RenderTargetsOptimization() {
  95292. return _super !== null && _super.apply(this, arguments) || this;
  95293. }
  95294. /**
  95295. * Gets a string describing the action executed by the current optimization
  95296. * @return description string
  95297. */
  95298. RenderTargetsOptimization.prototype.getDescription = function () {
  95299. return "Turning render targets off";
  95300. };
  95301. /**
  95302. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95303. * @param scene defines the current scene where to apply this optimization
  95304. * @param optimizer defines the current optimizer
  95305. * @returns true if everything that can be done was applied
  95306. */
  95307. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95308. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95309. return true;
  95310. };
  95311. ;
  95312. return RenderTargetsOptimization;
  95313. }(SceneOptimization));
  95314. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95315. /**
  95316. * Defines an optimization used to merge meshes with compatible materials
  95317. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95318. */
  95319. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95320. __extends(MergeMeshesOptimization, _super);
  95321. function MergeMeshesOptimization() {
  95322. var _this = _super !== null && _super.apply(this, arguments) || this;
  95323. _this._canBeMerged = function (abstractMesh) {
  95324. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95325. return false;
  95326. }
  95327. var mesh = abstractMesh;
  95328. if (!mesh.isVisible || !mesh.isEnabled()) {
  95329. return false;
  95330. }
  95331. if (mesh.instances.length > 0) {
  95332. return false;
  95333. }
  95334. if (mesh.skeleton || mesh.hasLODLevels) {
  95335. return false;
  95336. }
  95337. if (mesh.parent) {
  95338. return false;
  95339. }
  95340. return true;
  95341. };
  95342. return _this;
  95343. }
  95344. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95345. /**
  95346. * Gets or sets a boolean which defines if optimization octree has to be updated
  95347. */
  95348. get: function () {
  95349. return MergeMeshesOptimization._UpdateSelectionTree;
  95350. },
  95351. /**
  95352. * Gets or sets a boolean which defines if optimization octree has to be updated
  95353. */
  95354. set: function (value) {
  95355. MergeMeshesOptimization._UpdateSelectionTree = value;
  95356. },
  95357. enumerable: true,
  95358. configurable: true
  95359. });
  95360. /**
  95361. * Gets a string describing the action executed by the current optimization
  95362. * @return description string
  95363. */
  95364. MergeMeshesOptimization.prototype.getDescription = function () {
  95365. return "Merging similar meshes together";
  95366. };
  95367. /**
  95368. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95369. * @param scene defines the current scene where to apply this optimization
  95370. * @param optimizer defines the current optimizer
  95371. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95372. * @returns true if everything that can be done was applied
  95373. */
  95374. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95375. var globalPool = scene.meshes.slice(0);
  95376. var globalLength = globalPool.length;
  95377. for (var index = 0; index < globalLength; index++) {
  95378. var currentPool = new Array();
  95379. var current = globalPool[index];
  95380. // Checks
  95381. if (!this._canBeMerged(current)) {
  95382. continue;
  95383. }
  95384. currentPool.push(current);
  95385. // Find compatible meshes
  95386. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95387. var otherMesh = globalPool[subIndex];
  95388. if (!this._canBeMerged(otherMesh)) {
  95389. continue;
  95390. }
  95391. if (otherMesh.material !== current.material) {
  95392. continue;
  95393. }
  95394. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95395. continue;
  95396. }
  95397. currentPool.push(otherMesh);
  95398. globalLength--;
  95399. globalPool.splice(subIndex, 1);
  95400. subIndex--;
  95401. }
  95402. if (currentPool.length < 2) {
  95403. continue;
  95404. }
  95405. // Merge meshes
  95406. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95407. }
  95408. if (updateSelectionTree != undefined) {
  95409. if (updateSelectionTree) {
  95410. scene.createOrUpdateSelectionOctree();
  95411. }
  95412. }
  95413. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95414. scene.createOrUpdateSelectionOctree();
  95415. }
  95416. return true;
  95417. };
  95418. ;
  95419. MergeMeshesOptimization._UpdateSelectionTree = false;
  95420. return MergeMeshesOptimization;
  95421. }(SceneOptimization));
  95422. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95423. /**
  95424. * Defines a list of options used by SceneOptimizer
  95425. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95426. */
  95427. var SceneOptimizerOptions = /** @class */ (function () {
  95428. /**
  95429. * Creates a new list of options used by SceneOptimizer
  95430. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95431. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95432. */
  95433. function SceneOptimizerOptions(
  95434. /**
  95435. * Defines the target frame rate to reach (60 by default)
  95436. */
  95437. targetFrameRate,
  95438. /**
  95439. * Defines the interval between two checkes (2000ms by default)
  95440. */
  95441. trackerDuration) {
  95442. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95443. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95444. this.targetFrameRate = targetFrameRate;
  95445. this.trackerDuration = trackerDuration;
  95446. /**
  95447. * Gets the list of optimizations to apply
  95448. */
  95449. this.optimizations = new Array();
  95450. }
  95451. /**
  95452. * Add a new optimization
  95453. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95454. * @returns the current SceneOptimizerOptions
  95455. */
  95456. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95457. this.optimizations.push(optimization);
  95458. return this;
  95459. };
  95460. /**
  95461. * Add a new custom optimization
  95462. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95463. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95464. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95465. * @returns the current SceneOptimizerOptions
  95466. */
  95467. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95468. if (priority === void 0) { priority = 0; }
  95469. var optimization = new CustomOptimization(priority);
  95470. optimization.onApply = onApply;
  95471. optimization.onGetDescription = onGetDescription;
  95472. this.optimizations.push(optimization);
  95473. return this;
  95474. };
  95475. /**
  95476. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95477. * @param targetFrameRate defines the target frame rate (60 by default)
  95478. * @returns a SceneOptimizerOptions object
  95479. */
  95480. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95481. var result = new SceneOptimizerOptions(targetFrameRate);
  95482. var priority = 0;
  95483. result.addOptimization(new MergeMeshesOptimization(priority));
  95484. result.addOptimization(new ShadowsOptimization(priority));
  95485. result.addOptimization(new LensFlaresOptimization(priority));
  95486. // Next priority
  95487. priority++;
  95488. result.addOptimization(new PostProcessesOptimization(priority));
  95489. result.addOptimization(new ParticlesOptimization(priority));
  95490. // Next priority
  95491. priority++;
  95492. result.addOptimization(new TextureOptimization(priority, 1024));
  95493. return result;
  95494. };
  95495. /**
  95496. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95497. * @param targetFrameRate defines the target frame rate (60 by default)
  95498. * @returns a SceneOptimizerOptions object
  95499. */
  95500. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95501. var result = new SceneOptimizerOptions(targetFrameRate);
  95502. var priority = 0;
  95503. result.addOptimization(new MergeMeshesOptimization(priority));
  95504. result.addOptimization(new ShadowsOptimization(priority));
  95505. result.addOptimization(new LensFlaresOptimization(priority));
  95506. // Next priority
  95507. priority++;
  95508. result.addOptimization(new PostProcessesOptimization(priority));
  95509. result.addOptimization(new ParticlesOptimization(priority));
  95510. // Next priority
  95511. priority++;
  95512. result.addOptimization(new TextureOptimization(priority, 512));
  95513. // Next priority
  95514. priority++;
  95515. result.addOptimization(new RenderTargetsOptimization(priority));
  95516. // Next priority
  95517. priority++;
  95518. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95519. return result;
  95520. };
  95521. /**
  95522. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95523. * @param targetFrameRate defines the target frame rate (60 by default)
  95524. * @returns a SceneOptimizerOptions object
  95525. */
  95526. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95527. var result = new SceneOptimizerOptions(targetFrameRate);
  95528. var priority = 0;
  95529. result.addOptimization(new MergeMeshesOptimization(priority));
  95530. result.addOptimization(new ShadowsOptimization(priority));
  95531. result.addOptimization(new LensFlaresOptimization(priority));
  95532. // Next priority
  95533. priority++;
  95534. result.addOptimization(new PostProcessesOptimization(priority));
  95535. result.addOptimization(new ParticlesOptimization(priority));
  95536. // Next priority
  95537. priority++;
  95538. result.addOptimization(new TextureOptimization(priority, 256));
  95539. // Next priority
  95540. priority++;
  95541. result.addOptimization(new RenderTargetsOptimization(priority));
  95542. // Next priority
  95543. priority++;
  95544. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95545. return result;
  95546. };
  95547. return SceneOptimizerOptions;
  95548. }());
  95549. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95550. /**
  95551. * Class used to run optimizations in order to reach a target frame rate
  95552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95553. */
  95554. var SceneOptimizer = /** @class */ (function () {
  95555. /**
  95556. * Creates a new SceneOptimizer
  95557. * @param scene defines the scene to work on
  95558. * @param options defines the options to use with the SceneOptimizer
  95559. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95560. * @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)
  95561. */
  95562. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95563. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95564. if (improvementMode === void 0) { improvementMode = false; }
  95565. var _this = this;
  95566. this._isRunning = false;
  95567. this._currentPriorityLevel = 0;
  95568. this._targetFrameRate = 60;
  95569. this._trackerDuration = 2000;
  95570. this._currentFrameRate = 0;
  95571. this._improvementMode = false;
  95572. /**
  95573. * Defines an observable called when the optimizer reaches the target frame rate
  95574. */
  95575. this.onSuccessObservable = new BABYLON.Observable();
  95576. /**
  95577. * Defines an observable called when the optimizer enables an optimization
  95578. */
  95579. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95580. /**
  95581. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95582. */
  95583. this.onFailureObservable = new BABYLON.Observable();
  95584. if (!options) {
  95585. this._options = new SceneOptimizerOptions();
  95586. }
  95587. else {
  95588. this._options = options;
  95589. }
  95590. if (this._options.targetFrameRate) {
  95591. this._targetFrameRate = this._options.targetFrameRate;
  95592. }
  95593. if (this._options.trackerDuration) {
  95594. this._trackerDuration = this._options.trackerDuration;
  95595. }
  95596. if (autoGeneratePriorities) {
  95597. var priority = 0;
  95598. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95599. var optim = _a[_i];
  95600. optim.priority = priority++;
  95601. }
  95602. }
  95603. this._improvementMode = improvementMode;
  95604. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95605. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95606. _this._sceneDisposeObserver = null;
  95607. _this.dispose();
  95608. });
  95609. }
  95610. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95611. /**
  95612. * Gets a boolean indicating if the optimizer is in improvement mode
  95613. */
  95614. get: function () {
  95615. return this._improvementMode;
  95616. },
  95617. enumerable: true,
  95618. configurable: true
  95619. });
  95620. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95621. /**
  95622. * Gets the current priority level (0 at start)
  95623. */
  95624. get: function () {
  95625. return this._currentPriorityLevel;
  95626. },
  95627. enumerable: true,
  95628. configurable: true
  95629. });
  95630. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95631. /**
  95632. * Gets the current frame rate checked by the SceneOptimizer
  95633. */
  95634. get: function () {
  95635. return this._currentFrameRate;
  95636. },
  95637. enumerable: true,
  95638. configurable: true
  95639. });
  95640. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95641. /**
  95642. * Gets or sets the current target frame rate (60 by default)
  95643. */
  95644. get: function () {
  95645. return this._targetFrameRate;
  95646. },
  95647. /**
  95648. * Gets or sets the current target frame rate (60 by default)
  95649. */
  95650. set: function (value) {
  95651. this._targetFrameRate = value;
  95652. },
  95653. enumerable: true,
  95654. configurable: true
  95655. });
  95656. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95657. /**
  95658. * Gets or sets the current interval between two checks (every 2000ms by default)
  95659. */
  95660. get: function () {
  95661. return this._trackerDuration;
  95662. },
  95663. /**
  95664. * Gets or sets the current interval between two checks (every 2000ms by default)
  95665. */
  95666. set: function (value) {
  95667. this._trackerDuration = value;
  95668. },
  95669. enumerable: true,
  95670. configurable: true
  95671. });
  95672. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95673. /**
  95674. * Gets the list of active optimizations
  95675. */
  95676. get: function () {
  95677. return this._options.optimizations;
  95678. },
  95679. enumerable: true,
  95680. configurable: true
  95681. });
  95682. /**
  95683. * Stops the current optimizer
  95684. */
  95685. SceneOptimizer.prototype.stop = function () {
  95686. this._isRunning = false;
  95687. };
  95688. /**
  95689. * Reset the optimizer to initial step (current priority level = 0)
  95690. */
  95691. SceneOptimizer.prototype.reset = function () {
  95692. this._currentPriorityLevel = 0;
  95693. };
  95694. /**
  95695. * Start the optimizer. By default it will try to reach a specific framerate
  95696. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95697. */
  95698. SceneOptimizer.prototype.start = function () {
  95699. var _this = this;
  95700. if (this._isRunning) {
  95701. return;
  95702. }
  95703. this._isRunning = true;
  95704. // Let's wait for the scene to be ready before running our check
  95705. this._scene.executeWhenReady(function () {
  95706. setTimeout(function () {
  95707. _this._checkCurrentState();
  95708. }, _this._trackerDuration);
  95709. });
  95710. };
  95711. SceneOptimizer.prototype._checkCurrentState = function () {
  95712. var _this = this;
  95713. if (!this._isRunning) {
  95714. return;
  95715. }
  95716. var scene = this._scene;
  95717. var options = this._options;
  95718. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95719. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95720. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95721. this._isRunning = false;
  95722. this.onSuccessObservable.notifyObservers(this);
  95723. return;
  95724. }
  95725. // Apply current level of optimizations
  95726. var allDone = true;
  95727. var noOptimizationApplied = true;
  95728. for (var index = 0; index < options.optimizations.length; index++) {
  95729. var optimization = options.optimizations[index];
  95730. if (optimization.priority === this._currentPriorityLevel) {
  95731. noOptimizationApplied = false;
  95732. allDone = allDone && optimization.apply(scene, this);
  95733. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95734. }
  95735. }
  95736. // If no optimization was applied, this is a failure :(
  95737. if (noOptimizationApplied) {
  95738. this._isRunning = false;
  95739. this.onFailureObservable.notifyObservers(this);
  95740. return;
  95741. }
  95742. // If all optimizations were done, move to next level
  95743. if (allDone) {
  95744. this._currentPriorityLevel++;
  95745. }
  95746. // Let's the system running for a specific amount of time before checking FPS
  95747. scene.executeWhenReady(function () {
  95748. setTimeout(function () {
  95749. _this._checkCurrentState();
  95750. }, _this._trackerDuration);
  95751. });
  95752. };
  95753. /**
  95754. * Release all resources
  95755. */
  95756. SceneOptimizer.prototype.dispose = function () {
  95757. this.stop();
  95758. this.onSuccessObservable.clear();
  95759. this.onFailureObservable.clear();
  95760. this.onNewOptimizationAppliedObservable.clear();
  95761. if (this._sceneDisposeObserver) {
  95762. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95763. }
  95764. };
  95765. /**
  95766. * Helper function to create a SceneOptimizer with one single line of code
  95767. * @param scene defines the scene to work on
  95768. * @param options defines the options to use with the SceneOptimizer
  95769. * @param onSuccess defines a callback to call on success
  95770. * @param onFailure defines a callback to call on failure
  95771. * @returns the new SceneOptimizer object
  95772. */
  95773. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95774. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95775. if (onSuccess) {
  95776. optimizer.onSuccessObservable.add(function () {
  95777. onSuccess();
  95778. });
  95779. }
  95780. if (onFailure) {
  95781. optimizer.onFailureObservable.add(function () {
  95782. onFailure();
  95783. });
  95784. }
  95785. optimizer.start();
  95786. return optimizer;
  95787. };
  95788. return SceneOptimizer;
  95789. }());
  95790. BABYLON.SceneOptimizer = SceneOptimizer;
  95791. })(BABYLON || (BABYLON = {}));
  95792. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95793. var BABYLON;
  95794. (function (BABYLON) {
  95795. var OutlineRenderer = /** @class */ (function () {
  95796. function OutlineRenderer(scene) {
  95797. this.zOffset = 1;
  95798. this._scene = scene;
  95799. }
  95800. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95801. var _this = this;
  95802. if (useOverlay === void 0) { useOverlay = false; }
  95803. var scene = this._scene;
  95804. var engine = this._scene.getEngine();
  95805. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95806. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95807. return;
  95808. }
  95809. var mesh = subMesh.getRenderingMesh();
  95810. var material = subMesh.getMaterial();
  95811. if (!material || !scene.activeCamera) {
  95812. return;
  95813. }
  95814. engine.enableEffect(this._effect);
  95815. // Logarithmic depth
  95816. if (material.useLogarithmicDepth) {
  95817. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95818. }
  95819. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95820. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95821. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95822. // Bones
  95823. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95824. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95825. }
  95826. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95827. // Alpha test
  95828. if (material && material.needAlphaTesting()) {
  95829. var alphaTexture = material.getAlphaTestTexture();
  95830. if (alphaTexture) {
  95831. this._effect.setTexture("diffuseSampler", alphaTexture);
  95832. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95833. }
  95834. }
  95835. engine.setZOffset(-this.zOffset);
  95836. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95837. engine.setZOffset(0);
  95838. };
  95839. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95840. var defines = [];
  95841. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95842. var mesh = subMesh.getMesh();
  95843. var material = subMesh.getMaterial();
  95844. if (material) {
  95845. // Alpha test
  95846. if (material.needAlphaTesting()) {
  95847. defines.push("#define ALPHATEST");
  95848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95849. attribs.push(BABYLON.VertexBuffer.UVKind);
  95850. defines.push("#define UV1");
  95851. }
  95852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95854. defines.push("#define UV2");
  95855. }
  95856. }
  95857. //Logarithmic depth
  95858. if (material.useLogarithmicDepth) {
  95859. defines.push("#define LOGARITHMICDEPTH");
  95860. }
  95861. }
  95862. // Bones
  95863. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95864. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95865. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95866. if (mesh.numBoneInfluencers > 4) {
  95867. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95868. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95869. }
  95870. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95871. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95872. }
  95873. else {
  95874. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95875. }
  95876. // Instances
  95877. if (useInstances) {
  95878. defines.push("#define INSTANCES");
  95879. attribs.push("world0");
  95880. attribs.push("world1");
  95881. attribs.push("world2");
  95882. attribs.push("world3");
  95883. }
  95884. // Get correct effect
  95885. var join = defines.join("\n");
  95886. if (this._cachedDefines !== join) {
  95887. this._cachedDefines = join;
  95888. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95889. }
  95890. return this._effect.isReady();
  95891. };
  95892. return OutlineRenderer;
  95893. }());
  95894. BABYLON.OutlineRenderer = OutlineRenderer;
  95895. })(BABYLON || (BABYLON = {}));
  95896. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95897. var BABYLON;
  95898. (function (BABYLON) {
  95899. var FaceAdjacencies = /** @class */ (function () {
  95900. function FaceAdjacencies() {
  95901. this.edges = new Array();
  95902. this.edgesConnectedCount = 0;
  95903. }
  95904. return FaceAdjacencies;
  95905. }());
  95906. var EdgesRenderer = /** @class */ (function () {
  95907. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95908. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95909. if (epsilon === void 0) { epsilon = 0.95; }
  95910. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95911. this.edgesWidthScalerForOrthographic = 1000.0;
  95912. this.edgesWidthScalerForPerspective = 50.0;
  95913. this._linesPositions = new Array();
  95914. this._linesNormals = new Array();
  95915. this._linesIndices = new Array();
  95916. this._buffers = {};
  95917. this._checkVerticesInsteadOfIndices = false;
  95918. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95919. this.isEnabled = true;
  95920. this._source = source;
  95921. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95922. this._epsilon = epsilon;
  95923. this._prepareRessources();
  95924. this._generateEdgesLines();
  95925. }
  95926. EdgesRenderer.prototype._prepareRessources = function () {
  95927. if (this._lineShader) {
  95928. return;
  95929. }
  95930. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95931. attributes: ["position", "normal"],
  95932. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95933. });
  95934. this._lineShader.disableDepthWrite = true;
  95935. this._lineShader.backFaceCulling = false;
  95936. };
  95937. EdgesRenderer.prototype._rebuild = function () {
  95938. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95939. if (buffer) {
  95940. buffer._rebuild();
  95941. }
  95942. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95943. if (buffer) {
  95944. buffer._rebuild();
  95945. }
  95946. var scene = this._source.getScene();
  95947. var engine = scene.getEngine();
  95948. this._ib = engine.createIndexBuffer(this._linesIndices);
  95949. };
  95950. EdgesRenderer.prototype.dispose = function () {
  95951. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95952. if (buffer) {
  95953. buffer.dispose();
  95954. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95955. }
  95956. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95957. if (buffer) {
  95958. buffer.dispose();
  95959. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95960. }
  95961. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95962. this._lineShader.dispose();
  95963. };
  95964. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95965. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95966. return 0;
  95967. }
  95968. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95969. return 1;
  95970. }
  95971. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95972. return 2;
  95973. }
  95974. return -1;
  95975. };
  95976. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95977. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95978. return 0;
  95979. }
  95980. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95981. return 1;
  95982. }
  95983. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95984. return 2;
  95985. }
  95986. return -1;
  95987. };
  95988. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95989. var needToCreateLine;
  95990. if (edge === undefined) {
  95991. needToCreateLine = true;
  95992. }
  95993. else {
  95994. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95995. needToCreateLine = dotProduct < this._epsilon;
  95996. }
  95997. if (needToCreateLine) {
  95998. var offset = this._linesPositions.length / 3;
  95999. var normal = p0.subtract(p1);
  96000. normal.normalize();
  96001. // Positions
  96002. this._linesPositions.push(p0.x);
  96003. this._linesPositions.push(p0.y);
  96004. this._linesPositions.push(p0.z);
  96005. this._linesPositions.push(p0.x);
  96006. this._linesPositions.push(p0.y);
  96007. this._linesPositions.push(p0.z);
  96008. this._linesPositions.push(p1.x);
  96009. this._linesPositions.push(p1.y);
  96010. this._linesPositions.push(p1.z);
  96011. this._linesPositions.push(p1.x);
  96012. this._linesPositions.push(p1.y);
  96013. this._linesPositions.push(p1.z);
  96014. // Normals
  96015. this._linesNormals.push(p1.x);
  96016. this._linesNormals.push(p1.y);
  96017. this._linesNormals.push(p1.z);
  96018. this._linesNormals.push(-1);
  96019. this._linesNormals.push(p1.x);
  96020. this._linesNormals.push(p1.y);
  96021. this._linesNormals.push(p1.z);
  96022. this._linesNormals.push(1);
  96023. this._linesNormals.push(p0.x);
  96024. this._linesNormals.push(p0.y);
  96025. this._linesNormals.push(p0.z);
  96026. this._linesNormals.push(-1);
  96027. this._linesNormals.push(p0.x);
  96028. this._linesNormals.push(p0.y);
  96029. this._linesNormals.push(p0.z);
  96030. this._linesNormals.push(1);
  96031. // Indices
  96032. this._linesIndices.push(offset);
  96033. this._linesIndices.push(offset + 1);
  96034. this._linesIndices.push(offset + 2);
  96035. this._linesIndices.push(offset);
  96036. this._linesIndices.push(offset + 2);
  96037. this._linesIndices.push(offset + 3);
  96038. }
  96039. };
  96040. EdgesRenderer.prototype._generateEdgesLines = function () {
  96041. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96042. var indices = this._source.getIndices();
  96043. if (!indices || !positions) {
  96044. return;
  96045. }
  96046. // First let's find adjacencies
  96047. var adjacencies = new Array();
  96048. var faceNormals = new Array();
  96049. var index;
  96050. var faceAdjacencies;
  96051. // Prepare faces
  96052. for (index = 0; index < indices.length; index += 3) {
  96053. faceAdjacencies = new FaceAdjacencies();
  96054. var p0Index = indices[index];
  96055. var p1Index = indices[index + 1];
  96056. var p2Index = indices[index + 2];
  96057. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96058. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96059. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96060. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96061. faceNormal.normalize();
  96062. faceNormals.push(faceNormal);
  96063. adjacencies.push(faceAdjacencies);
  96064. }
  96065. // Scan
  96066. for (index = 0; index < adjacencies.length; index++) {
  96067. faceAdjacencies = adjacencies[index];
  96068. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96069. var otherFaceAdjacencies = adjacencies[otherIndex];
  96070. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96071. break;
  96072. }
  96073. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96074. continue;
  96075. }
  96076. var otherP0 = indices[otherIndex * 3];
  96077. var otherP1 = indices[otherIndex * 3 + 1];
  96078. var otherP2 = indices[otherIndex * 3 + 2];
  96079. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96080. var otherEdgeIndex = 0;
  96081. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96082. continue;
  96083. }
  96084. switch (edgeIndex) {
  96085. case 0:
  96086. if (this._checkVerticesInsteadOfIndices) {
  96087. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96088. }
  96089. else {
  96090. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96091. }
  96092. break;
  96093. case 1:
  96094. if (this._checkVerticesInsteadOfIndices) {
  96095. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96096. }
  96097. else {
  96098. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96099. }
  96100. break;
  96101. case 2:
  96102. if (this._checkVerticesInsteadOfIndices) {
  96103. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96104. }
  96105. else {
  96106. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96107. }
  96108. break;
  96109. }
  96110. if (otherEdgeIndex === -1) {
  96111. continue;
  96112. }
  96113. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96114. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96115. faceAdjacencies.edgesConnectedCount++;
  96116. otherFaceAdjacencies.edgesConnectedCount++;
  96117. if (faceAdjacencies.edgesConnectedCount === 3) {
  96118. break;
  96119. }
  96120. }
  96121. }
  96122. }
  96123. // Create lines
  96124. for (index = 0; index < adjacencies.length; index++) {
  96125. // 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
  96126. var current = adjacencies[index];
  96127. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96128. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96129. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96130. }
  96131. // Merge into a single mesh
  96132. var engine = this._source.getScene().getEngine();
  96133. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96134. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96135. this._ib = engine.createIndexBuffer(this._linesIndices);
  96136. this._indicesCount = this._linesIndices.length;
  96137. };
  96138. EdgesRenderer.prototype.render = function () {
  96139. var scene = this._source.getScene();
  96140. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96141. return;
  96142. }
  96143. var engine = scene.getEngine();
  96144. this._lineShader._preBind();
  96145. // VBOs
  96146. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96147. scene.resetCachedMaterial();
  96148. this._lineShader.setColor4("color", this._source.edgesColor);
  96149. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96150. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96151. }
  96152. else {
  96153. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96154. }
  96155. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96156. this._lineShader.bind(this._source.getWorldMatrix());
  96157. // Draw order
  96158. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96159. this._lineShader.unbind();
  96160. engine.setDepthWrite(true);
  96161. };
  96162. return EdgesRenderer;
  96163. }());
  96164. BABYLON.EdgesRenderer = EdgesRenderer;
  96165. })(BABYLON || (BABYLON = {}));
  96166. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96167. var BABYLON;
  96168. (function (BABYLON) {
  96169. // Adds the parser to the scene parsers.
  96170. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96171. if (parsedData.effectLayers) {
  96172. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96173. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96174. container.effectLayers.push(effectLayer);
  96175. }
  96176. }
  96177. });
  96178. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96179. var index = this.effectLayers.indexOf(toRemove);
  96180. if (index !== -1) {
  96181. this.effectLayers.splice(index, 1);
  96182. }
  96183. return index;
  96184. };
  96185. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96186. this.effectLayers.push(newEffectLayer);
  96187. };
  96188. /**
  96189. * Defines the layer scene component responsible to manage any effect layers
  96190. * in a given scene.
  96191. */
  96192. var EffectLayerSceneComponent = /** @class */ (function () {
  96193. /**
  96194. * Creates a new instance of the component for the given scene
  96195. * @param scene Defines the scene to register the component in
  96196. */
  96197. function EffectLayerSceneComponent(scene) {
  96198. /**
  96199. * The component name helpfull to identify the component in the list of scene components.
  96200. */
  96201. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96202. this._renderEffects = false;
  96203. this._needStencil = false;
  96204. this._previousStencilState = false;
  96205. this.scene = scene;
  96206. this._engine = scene.getEngine();
  96207. this._effectLayers = scene.effectLayers = new Array();
  96208. }
  96209. /**
  96210. * Registers the component in a given scene
  96211. */
  96212. EffectLayerSceneComponent.prototype.register = function () {
  96213. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96214. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96215. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96216. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96217. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96218. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96219. };
  96220. /**
  96221. * Rebuilds the elements related to this component in case of
  96222. * context lost for instance.
  96223. */
  96224. EffectLayerSceneComponent.prototype.rebuild = function () {
  96225. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96226. var effectLayer = _a[_i];
  96227. effectLayer._rebuild();
  96228. }
  96229. };
  96230. /**
  96231. * Serializes the component data to the specified json object
  96232. * @param serializationObject The object to serialize to
  96233. */
  96234. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96235. // Effect layers
  96236. serializationObject.effectLayers = [];
  96237. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96238. var effectLayer = _a[_i];
  96239. if (effectLayer.serialize) {
  96240. serializationObject.effectLayers.push(effectLayer.serialize());
  96241. }
  96242. }
  96243. };
  96244. /**
  96245. * Adds all the element from the container to the scene
  96246. * @param container the container holding the elements
  96247. */
  96248. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96249. var _this = this;
  96250. if (!container.effectLayers) {
  96251. return;
  96252. }
  96253. container.effectLayers.forEach(function (o) {
  96254. _this.scene.addEffectLayer(o);
  96255. });
  96256. };
  96257. /**
  96258. * Removes all the elements in the container from the scene
  96259. * @param container contains the elements to remove
  96260. */
  96261. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96262. var _this = this;
  96263. if (!container.effectLayers) {
  96264. return;
  96265. }
  96266. container.effectLayers.forEach(function (o) {
  96267. _this.scene.removeEffectLayer(o);
  96268. });
  96269. };
  96270. /**
  96271. * Disposes the component and the associated ressources.
  96272. */
  96273. EffectLayerSceneComponent.prototype.dispose = function () {
  96274. while (this._effectLayers.length) {
  96275. this._effectLayers[0].dispose();
  96276. }
  96277. };
  96278. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96279. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96280. var layer = _a[_i];
  96281. if (!layer.hasMesh(mesh)) {
  96282. continue;
  96283. }
  96284. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  96285. var subMesh = _c[_b];
  96286. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96287. return false;
  96288. }
  96289. }
  96290. }
  96291. return true;
  96292. };
  96293. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96294. this._renderEffects = false;
  96295. this._needStencil = false;
  96296. if (this._effectLayers && this._effectLayers.length > 0) {
  96297. this._previousStencilState = this._engine.getStencilBuffer();
  96298. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96299. var effectLayer = _a[_i];
  96300. if (effectLayer.shouldRender() &&
  96301. (!effectLayer.camera ||
  96302. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96303. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96304. this._renderEffects = true;
  96305. this._needStencil = this._needStencil || effectLayer.needStencil();
  96306. var renderTarget = effectLayer._mainTexture;
  96307. if (renderTarget._shouldRender()) {
  96308. this.scene.incrementRenderId();
  96309. renderTarget.render(false, false);
  96310. }
  96311. }
  96312. }
  96313. this.scene.incrementRenderId();
  96314. }
  96315. };
  96316. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96317. // Activate effect Layer stencil
  96318. if (this._needStencil) {
  96319. this._engine.setStencilBuffer(true);
  96320. }
  96321. };
  96322. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96323. // Restore effect Layer stencil
  96324. if (this._needStencil) {
  96325. this._engine.setStencilBuffer(this._previousStencilState);
  96326. }
  96327. };
  96328. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96329. if (this._renderEffects) {
  96330. this._engine.setDepthBuffer(false);
  96331. for (var i = 0; i < this._effectLayers.length; i++) {
  96332. var effectLayer = this._effectLayers[i];
  96333. if (effectLayer.renderingGroupId === renderingGroupId) {
  96334. if (effectLayer.shouldRender()) {
  96335. effectLayer.render();
  96336. }
  96337. }
  96338. }
  96339. this._engine.setDepthBuffer(true);
  96340. }
  96341. };
  96342. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96343. if (this._renderEffects) {
  96344. this._draw(-1);
  96345. }
  96346. };
  96347. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96348. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96349. this._draw(index);
  96350. }
  96351. };
  96352. return EffectLayerSceneComponent;
  96353. }());
  96354. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96355. })(BABYLON || (BABYLON = {}));
  96356. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96357. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96358. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96359. s = arguments[i];
  96360. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96361. t[p] = s[p];
  96362. }
  96363. return t;
  96364. };
  96365. var BABYLON;
  96366. (function (BABYLON) {
  96367. /**
  96368. * The effect layer Helps adding post process effect blended with the main pass.
  96369. *
  96370. * This can be for instance use to generate glow or higlight effects on the scene.
  96371. *
  96372. * The effect layer class can not be used directly and is intented to inherited from to be
  96373. * customized per effects.
  96374. */
  96375. var EffectLayer = /** @class */ (function () {
  96376. /**
  96377. * Instantiates a new effect Layer and references it in the scene.
  96378. * @param name The name of the layer
  96379. * @param scene The scene to use the layer in
  96380. */
  96381. function EffectLayer(
  96382. /** The Friendly of the effect in the scene */
  96383. name, scene) {
  96384. this._vertexBuffers = {};
  96385. this._maxSize = 0;
  96386. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96387. this._shouldRender = true;
  96388. this._postProcesses = [];
  96389. this._textures = [];
  96390. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96391. /**
  96392. * The clear color of the texture used to generate the glow map.
  96393. */
  96394. this.neutralColor = new BABYLON.Color4();
  96395. /**
  96396. * Specifies wether the highlight layer is enabled or not.
  96397. */
  96398. this.isEnabled = true;
  96399. /**
  96400. * An event triggered when the effect layer has been disposed.
  96401. */
  96402. this.onDisposeObservable = new BABYLON.Observable();
  96403. /**
  96404. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96405. */
  96406. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96407. /**
  96408. * An event triggered when the generated texture is being merged in the scene.
  96409. */
  96410. this.onBeforeComposeObservable = new BABYLON.Observable();
  96411. /**
  96412. * An event triggered when the generated texture has been merged in the scene.
  96413. */
  96414. this.onAfterComposeObservable = new BABYLON.Observable();
  96415. /**
  96416. * An event triggered when the efffect layer changes its size.
  96417. */
  96418. this.onSizeChangedObservable = new BABYLON.Observable();
  96419. this.name = name;
  96420. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96421. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96422. if (!component) {
  96423. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96424. this._scene._addComponent(component);
  96425. }
  96426. this._engine = this._scene.getEngine();
  96427. this._maxSize = this._engine.getCaps().maxTextureSize;
  96428. this._scene.effectLayers.push(this);
  96429. // Generate Buffers
  96430. this._generateIndexBuffer();
  96431. this._genrateVertexBuffer();
  96432. }
  96433. Object.defineProperty(EffectLayer.prototype, "camera", {
  96434. /**
  96435. * Gets the camera attached to the layer.
  96436. */
  96437. get: function () {
  96438. return this._effectLayerOptions.camera;
  96439. },
  96440. enumerable: true,
  96441. configurable: true
  96442. });
  96443. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96444. /**
  96445. * Gets the rendering group id the layer should render in.
  96446. */
  96447. get: function () {
  96448. return this._effectLayerOptions.renderingGroupId;
  96449. },
  96450. enumerable: true,
  96451. configurable: true
  96452. });
  96453. /**
  96454. * Initializes the effect layer with the required options.
  96455. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96456. */
  96457. EffectLayer.prototype._init = function (options) {
  96458. // Adapt options
  96459. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96460. this._setMainTextureSize();
  96461. this._createMainTexture();
  96462. this._createTextureAndPostProcesses();
  96463. this._mergeEffect = this._createMergeEffect();
  96464. };
  96465. /**
  96466. * Generates the index buffer of the full screen quad blending to the main canvas.
  96467. */
  96468. EffectLayer.prototype._generateIndexBuffer = function () {
  96469. // Indices
  96470. var indices = [];
  96471. indices.push(0);
  96472. indices.push(1);
  96473. indices.push(2);
  96474. indices.push(0);
  96475. indices.push(2);
  96476. indices.push(3);
  96477. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96478. };
  96479. /**
  96480. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96481. */
  96482. EffectLayer.prototype._genrateVertexBuffer = function () {
  96483. // VBO
  96484. var vertices = [];
  96485. vertices.push(1, 1);
  96486. vertices.push(-1, 1);
  96487. vertices.push(-1, -1);
  96488. vertices.push(1, -1);
  96489. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96490. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96491. };
  96492. /**
  96493. * Sets the main texture desired size which is the closest power of two
  96494. * of the engine canvas size.
  96495. */
  96496. EffectLayer.prototype._setMainTextureSize = function () {
  96497. if (this._effectLayerOptions.mainTextureFixedSize) {
  96498. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96499. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96500. }
  96501. else {
  96502. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96503. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96504. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96505. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96506. }
  96507. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96508. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96509. };
  96510. /**
  96511. * Creates the main texture for the effect layer.
  96512. */
  96513. EffectLayer.prototype._createMainTexture = function () {
  96514. var _this = this;
  96515. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96516. width: this._mainTextureDesiredSize.width,
  96517. height: this._mainTextureDesiredSize.height
  96518. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96519. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96520. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96521. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96522. this._mainTexture.anisotropicFilteringLevel = 1;
  96523. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96524. this._mainTexture.renderParticles = false;
  96525. this._mainTexture.renderList = null;
  96526. this._mainTexture.ignoreCameraViewport = true;
  96527. // Custom render function
  96528. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96529. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96530. var index;
  96531. var engine = _this._scene.getEngine();
  96532. if (depthOnlySubMeshes.length) {
  96533. engine.setColorWrite(false);
  96534. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96535. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96536. }
  96537. engine.setColorWrite(true);
  96538. }
  96539. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96540. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96541. }
  96542. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96543. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96544. }
  96545. for (index = 0; index < transparentSubMeshes.length; index++) {
  96546. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96547. }
  96548. };
  96549. this._mainTexture.onClearObservable.add(function (engine) {
  96550. engine.clear(_this.neutralColor, true, true, true);
  96551. });
  96552. };
  96553. /**
  96554. * Checks for the readiness of the element composing the layer.
  96555. * @param subMesh the mesh to check for
  96556. * @param useInstances specify wether or not to use instances to render the mesh
  96557. * @param emissiveTexture the associated emissive texture used to generate the glow
  96558. * @return true if ready otherwise, false
  96559. */
  96560. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96561. var material = subMesh.getMaterial();
  96562. if (!material) {
  96563. return false;
  96564. }
  96565. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96566. return false;
  96567. }
  96568. var defines = [];
  96569. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96570. var mesh = subMesh.getMesh();
  96571. var uv1 = false;
  96572. var uv2 = false;
  96573. // Alpha test
  96574. if (material && material.needAlphaTesting()) {
  96575. var alphaTexture = material.getAlphaTestTexture();
  96576. if (alphaTexture) {
  96577. defines.push("#define ALPHATEST");
  96578. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96579. alphaTexture.coordinatesIndex === 1) {
  96580. defines.push("#define DIFFUSEUV2");
  96581. uv2 = true;
  96582. }
  96583. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96584. defines.push("#define DIFFUSEUV1");
  96585. uv1 = true;
  96586. }
  96587. }
  96588. }
  96589. // Emissive
  96590. if (emissiveTexture) {
  96591. defines.push("#define EMISSIVE");
  96592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96593. emissiveTexture.coordinatesIndex === 1) {
  96594. defines.push("#define EMISSIVEUV2");
  96595. uv2 = true;
  96596. }
  96597. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96598. defines.push("#define EMISSIVEUV1");
  96599. uv1 = true;
  96600. }
  96601. }
  96602. if (uv1) {
  96603. attribs.push(BABYLON.VertexBuffer.UVKind);
  96604. defines.push("#define UV1");
  96605. }
  96606. if (uv2) {
  96607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96608. defines.push("#define UV2");
  96609. }
  96610. // Bones
  96611. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96614. if (mesh.numBoneInfluencers > 4) {
  96615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96617. }
  96618. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96619. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96620. }
  96621. else {
  96622. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96623. }
  96624. // Morph targets
  96625. var manager = mesh.morphTargetManager;
  96626. var morphInfluencers = 0;
  96627. if (manager) {
  96628. if (manager.numInfluencers > 0) {
  96629. defines.push("#define MORPHTARGETS");
  96630. morphInfluencers = manager.numInfluencers;
  96631. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96632. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96633. }
  96634. }
  96635. // Instances
  96636. if (useInstances) {
  96637. defines.push("#define INSTANCES");
  96638. attribs.push("world0");
  96639. attribs.push("world1");
  96640. attribs.push("world2");
  96641. attribs.push("world3");
  96642. }
  96643. // Get correct effect
  96644. var join = defines.join("\n");
  96645. if (this._cachedDefines !== join) {
  96646. this._cachedDefines = join;
  96647. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96648. }
  96649. return this._effectLayerMapGenerationEffect.isReady();
  96650. };
  96651. /**
  96652. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96653. */
  96654. EffectLayer.prototype.render = function () {
  96655. var currentEffect = this._mergeEffect;
  96656. // Check
  96657. if (!currentEffect.isReady())
  96658. return;
  96659. for (var i = 0; i < this._postProcesses.length; i++) {
  96660. if (!this._postProcesses[i].isReady()) {
  96661. return;
  96662. }
  96663. }
  96664. var engine = this._scene.getEngine();
  96665. this.onBeforeComposeObservable.notifyObservers(this);
  96666. // Render
  96667. engine.enableEffect(currentEffect);
  96668. engine.setState(false);
  96669. // VBOs
  96670. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96671. // Cache
  96672. var previousAlphaMode = engine.getAlphaMode();
  96673. // Go Blend.
  96674. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96675. // Blends the map on the main canvas.
  96676. this._internalRender(currentEffect);
  96677. // Restore Alpha
  96678. engine.setAlphaMode(previousAlphaMode);
  96679. this.onAfterComposeObservable.notifyObservers(this);
  96680. // Handle size changes.
  96681. var size = this._mainTexture.getSize();
  96682. this._setMainTextureSize();
  96683. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96684. // Recreate RTT and post processes on size change.
  96685. this.onSizeChangedObservable.notifyObservers(this);
  96686. this._disposeTextureAndPostProcesses();
  96687. this._createMainTexture();
  96688. this._createTextureAndPostProcesses();
  96689. }
  96690. };
  96691. /**
  96692. * Determine if a given mesh will be used in the current effect.
  96693. * @param mesh mesh to test
  96694. * @returns true if the mesh will be used
  96695. */
  96696. EffectLayer.prototype.hasMesh = function (mesh) {
  96697. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96698. return true;
  96699. }
  96700. return false;
  96701. };
  96702. /**
  96703. * Returns true if the layer contains information to display, otherwise false.
  96704. * @returns true if the glow layer should be rendered
  96705. */
  96706. EffectLayer.prototype.shouldRender = function () {
  96707. return this.isEnabled && this._shouldRender;
  96708. };
  96709. /**
  96710. * Returns true if the mesh should render, otherwise false.
  96711. * @param mesh The mesh to render
  96712. * @returns true if it should render otherwise false
  96713. */
  96714. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96715. return true;
  96716. };
  96717. /**
  96718. * Returns true if the mesh should render, otherwise false.
  96719. * @param mesh The mesh to render
  96720. * @returns true if it should render otherwise false
  96721. */
  96722. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96723. return true;
  96724. };
  96725. /**
  96726. * Renders the submesh passed in parameter to the generation map.
  96727. */
  96728. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96729. var _this = this;
  96730. if (!this.shouldRender()) {
  96731. return;
  96732. }
  96733. var material = subMesh.getMaterial();
  96734. var mesh = subMesh.getRenderingMesh();
  96735. var scene = this._scene;
  96736. var engine = scene.getEngine();
  96737. if (!material) {
  96738. return;
  96739. }
  96740. // Do not block in blend mode.
  96741. if (material.needAlphaBlendingForMesh(mesh)) {
  96742. return;
  96743. }
  96744. // Culling
  96745. engine.setState(material.backFaceCulling);
  96746. // Managing instances
  96747. var batch = mesh._getInstancesRenderList(subMesh._id);
  96748. if (batch.mustReturn) {
  96749. return;
  96750. }
  96751. // Early Exit per mesh
  96752. if (!this._shouldRenderMesh(mesh)) {
  96753. return;
  96754. }
  96755. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96756. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96757. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96758. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96759. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96760. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96761. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96762. // Alpha test
  96763. if (material && material.needAlphaTesting()) {
  96764. var alphaTexture = material.getAlphaTestTexture();
  96765. if (alphaTexture) {
  96766. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96767. var textureMatrix = alphaTexture.getTextureMatrix();
  96768. if (textureMatrix) {
  96769. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96770. }
  96771. }
  96772. }
  96773. // Glow emissive only
  96774. if (this._emissiveTextureAndColor.texture) {
  96775. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96776. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96777. }
  96778. // Bones
  96779. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96780. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96781. }
  96782. // Morph targets
  96783. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96784. // Draw
  96785. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96786. }
  96787. else {
  96788. // Need to reset refresh rate of the main map
  96789. this._mainTexture.resetRefreshCounter();
  96790. }
  96791. };
  96792. /**
  96793. * Rebuild the required buffers.
  96794. * @hidden Internal use only.
  96795. */
  96796. EffectLayer.prototype._rebuild = function () {
  96797. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96798. if (vb) {
  96799. vb._rebuild();
  96800. }
  96801. this._generateIndexBuffer();
  96802. };
  96803. /**
  96804. * Dispose only the render target textures and post process.
  96805. */
  96806. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96807. this._mainTexture.dispose();
  96808. for (var i = 0; i < this._postProcesses.length; i++) {
  96809. if (this._postProcesses[i]) {
  96810. this._postProcesses[i].dispose();
  96811. }
  96812. }
  96813. this._postProcesses = [];
  96814. for (var i = 0; i < this._textures.length; i++) {
  96815. if (this._textures[i]) {
  96816. this._textures[i].dispose();
  96817. }
  96818. }
  96819. this._textures = [];
  96820. };
  96821. /**
  96822. * Dispose the highlight layer and free resources.
  96823. */
  96824. EffectLayer.prototype.dispose = function () {
  96825. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96826. if (vertexBuffer) {
  96827. vertexBuffer.dispose();
  96828. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96829. }
  96830. if (this._indexBuffer) {
  96831. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96832. this._indexBuffer = null;
  96833. }
  96834. // Clean textures and post processes
  96835. this._disposeTextureAndPostProcesses();
  96836. // Remove from scene
  96837. var index = this._scene.effectLayers.indexOf(this, 0);
  96838. if (index > -1) {
  96839. this._scene.effectLayers.splice(index, 1);
  96840. }
  96841. // Callback
  96842. this.onDisposeObservable.notifyObservers(this);
  96843. this.onDisposeObservable.clear();
  96844. this.onBeforeRenderMainTextureObservable.clear();
  96845. this.onBeforeComposeObservable.clear();
  96846. this.onAfterComposeObservable.clear();
  96847. this.onSizeChangedObservable.clear();
  96848. };
  96849. /**
  96850. * Gets the class name of the effect layer
  96851. * @returns the string with the class name of the effect layer
  96852. */
  96853. EffectLayer.prototype.getClassName = function () {
  96854. return "EffectLayer";
  96855. };
  96856. /**
  96857. * Creates an effect layer from parsed effect layer data
  96858. * @param parsedEffectLayer defines effect layer data
  96859. * @param scene defines the current scene
  96860. * @param rootUrl defines the root URL containing the effect layer information
  96861. * @returns a parsed effect Layer
  96862. */
  96863. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96864. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96865. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96866. };
  96867. __decorate([
  96868. BABYLON.serialize()
  96869. ], EffectLayer.prototype, "name", void 0);
  96870. __decorate([
  96871. BABYLON.serializeAsColor4()
  96872. ], EffectLayer.prototype, "neutralColor", void 0);
  96873. __decorate([
  96874. BABYLON.serialize()
  96875. ], EffectLayer.prototype, "isEnabled", void 0);
  96876. __decorate([
  96877. BABYLON.serializeAsCameraReference()
  96878. ], EffectLayer.prototype, "camera", null);
  96879. __decorate([
  96880. BABYLON.serialize()
  96881. ], EffectLayer.prototype, "renderingGroupId", null);
  96882. return EffectLayer;
  96883. }());
  96884. BABYLON.EffectLayer = EffectLayer;
  96885. })(BABYLON || (BABYLON = {}));
  96886. //# sourceMappingURL=babylon.effectLayer.js.map
  96887. var BABYLON;
  96888. (function (BABYLON) {
  96889. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96890. for (var index = 0; index < this.effectLayers.length; index++) {
  96891. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96892. return this.effectLayers[index];
  96893. }
  96894. }
  96895. return null;
  96896. };
  96897. /**
  96898. * Special Glow Blur post process only blurring the alpha channel
  96899. * It enforces keeping the most luminous color in the color channel.
  96900. */
  96901. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96902. __extends(GlowBlurPostProcess, _super);
  96903. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96905. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96906. _this.direction = direction;
  96907. _this.kernel = kernel;
  96908. _this.onApplyObservable.add(function (effect) {
  96909. effect.setFloat2("screenSize", _this.width, _this.height);
  96910. effect.setVector2("direction", _this.direction);
  96911. effect.setFloat("blurWidth", _this.kernel);
  96912. });
  96913. return _this;
  96914. }
  96915. return GlowBlurPostProcess;
  96916. }(BABYLON.PostProcess));
  96917. /**
  96918. * The highlight layer Helps adding a glow effect around a mesh.
  96919. *
  96920. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96921. * glowy meshes to your scene.
  96922. *
  96923. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96924. */
  96925. var HighlightLayer = /** @class */ (function (_super) {
  96926. __extends(HighlightLayer, _super);
  96927. /**
  96928. * Instantiates a new highlight Layer and references it to the scene..
  96929. * @param name The name of the layer
  96930. * @param scene The scene to use the layer in
  96931. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96932. */
  96933. function HighlightLayer(name, scene, options) {
  96934. var _this = _super.call(this, name, scene) || this;
  96935. _this.name = name;
  96936. /**
  96937. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96938. */
  96939. _this.innerGlow = true;
  96940. /**
  96941. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96942. */
  96943. _this.outerGlow = true;
  96944. /**
  96945. * An event triggered when the highlight layer is being blurred.
  96946. */
  96947. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96948. /**
  96949. * An event triggered when the highlight layer has been blurred.
  96950. */
  96951. _this.onAfterBlurObservable = new BABYLON.Observable();
  96952. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96953. _this._meshes = {};
  96954. _this._excludedMeshes = {};
  96955. _this.neutralColor = HighlightLayer.NeutralColor;
  96956. // Warn on stencil
  96957. if (!_this._engine.isStencilEnable) {
  96958. 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 }");
  96959. }
  96960. // Adapt options
  96961. _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);
  96962. // Initialize the layer
  96963. _this._init({
  96964. alphaBlendingMode: _this._options.alphaBlendingMode,
  96965. camera: _this._options.camera,
  96966. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96967. mainTextureRatio: _this._options.mainTextureRatio,
  96968. renderingGroupId: _this._options.renderingGroupId
  96969. });
  96970. // Do not render as long as no meshes have been added
  96971. _this._shouldRender = false;
  96972. return _this;
  96973. }
  96974. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96975. /**
  96976. * Gets the horizontal size of the blur.
  96977. */
  96978. get: function () {
  96979. return this._horizontalBlurPostprocess.kernel;
  96980. },
  96981. /**
  96982. * Specifies the horizontal size of the blur.
  96983. */
  96984. set: function (value) {
  96985. this._horizontalBlurPostprocess.kernel = value;
  96986. },
  96987. enumerable: true,
  96988. configurable: true
  96989. });
  96990. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96991. /**
  96992. * Gets the vertical size of the blur.
  96993. */
  96994. get: function () {
  96995. return this._verticalBlurPostprocess.kernel;
  96996. },
  96997. /**
  96998. * Specifies the vertical size of the blur.
  96999. */
  97000. set: function (value) {
  97001. this._verticalBlurPostprocess.kernel = value;
  97002. },
  97003. enumerable: true,
  97004. configurable: true
  97005. });
  97006. /**
  97007. * Get the effect name of the layer.
  97008. * @return The effect name
  97009. */
  97010. HighlightLayer.prototype.getEffectName = function () {
  97011. return HighlightLayer.EffectName;
  97012. };
  97013. /**
  97014. * Create the merge effect. This is the shader use to blit the information back
  97015. * to the main canvas at the end of the scene rendering.
  97016. */
  97017. HighlightLayer.prototype._createMergeEffect = function () {
  97018. // Effect
  97019. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97020. };
  97021. /**
  97022. * Creates the render target textures and post processes used in the highlight layer.
  97023. */
  97024. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97025. var _this = this;
  97026. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97027. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97028. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97029. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97030. var textureType = 0;
  97031. if (this._engine.getCaps().textureHalfFloatRender) {
  97032. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97033. }
  97034. else {
  97035. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97036. }
  97037. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97038. width: blurTextureWidth,
  97039. height: blurTextureHeight
  97040. }, this._scene, false, true, textureType);
  97041. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97042. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97043. this._blurTexture.anisotropicFilteringLevel = 16;
  97044. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97045. this._blurTexture.renderParticles = false;
  97046. this._blurTexture.ignoreCameraViewport = true;
  97047. this._textures = [this._blurTexture];
  97048. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97049. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97050. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97051. effect.setTexture("textureSampler", _this._mainTexture);
  97052. });
  97053. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97054. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97055. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97056. });
  97057. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97058. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97059. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97060. });
  97061. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97062. }
  97063. else {
  97064. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97065. width: blurTextureWidth,
  97066. height: blurTextureHeight
  97067. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97068. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97069. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97070. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97071. effect.setTexture("textureSampler", _this._mainTexture);
  97072. });
  97073. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97074. width: blurTextureWidth,
  97075. height: blurTextureHeight
  97076. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97077. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97078. }
  97079. this._mainTexture.onAfterUnbindObservable.add(function () {
  97080. _this.onBeforeBlurObservable.notifyObservers(_this);
  97081. var internalTexture = _this._blurTexture.getInternalTexture();
  97082. if (internalTexture) {
  97083. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97084. }
  97085. _this.onAfterBlurObservable.notifyObservers(_this);
  97086. });
  97087. // Prevent autoClear.
  97088. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97089. };
  97090. /**
  97091. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97092. */
  97093. HighlightLayer.prototype.needStencil = function () {
  97094. return true;
  97095. };
  97096. /**
  97097. * Checks for the readiness of the element composing the layer.
  97098. * @param subMesh the mesh to check for
  97099. * @param useInstances specify wether or not to use instances to render the mesh
  97100. * @param emissiveTexture the associated emissive texture used to generate the glow
  97101. * @return true if ready otherwise, false
  97102. */
  97103. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97104. var material = subMesh.getMaterial();
  97105. var mesh = subMesh.getRenderingMesh();
  97106. if (!material || !mesh || !this._meshes) {
  97107. return false;
  97108. }
  97109. var emissiveTexture = null;
  97110. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97111. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97112. emissiveTexture = material.emissiveTexture;
  97113. }
  97114. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97115. };
  97116. /**
  97117. * Implementation specific of rendering the generating effect on the main canvas.
  97118. * @param effect The effect used to render through
  97119. */
  97120. HighlightLayer.prototype._internalRender = function (effect) {
  97121. // Texture
  97122. effect.setTexture("textureSampler", this._blurTexture);
  97123. // Cache
  97124. var engine = this._engine;
  97125. var previousStencilBuffer = engine.getStencilBuffer();
  97126. var previousStencilFunction = engine.getStencilFunction();
  97127. var previousStencilMask = engine.getStencilMask();
  97128. var previousStencilOperationPass = engine.getStencilOperationPass();
  97129. var previousStencilOperationFail = engine.getStencilOperationFail();
  97130. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97131. var previousStencilReference = engine.getStencilFunctionReference();
  97132. // Stencil operations
  97133. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97134. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97135. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97136. // Draw order
  97137. engine.setStencilMask(0x00);
  97138. engine.setStencilBuffer(true);
  97139. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97140. // 2 passes inner outer
  97141. if (this.outerGlow) {
  97142. effect.setFloat("offset", 0);
  97143. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97144. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97145. }
  97146. if (this.innerGlow) {
  97147. effect.setFloat("offset", 1);
  97148. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97149. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97150. }
  97151. // Restore Cache
  97152. engine.setStencilFunction(previousStencilFunction);
  97153. engine.setStencilMask(previousStencilMask);
  97154. engine.setStencilBuffer(previousStencilBuffer);
  97155. engine.setStencilOperationPass(previousStencilOperationPass);
  97156. engine.setStencilOperationFail(previousStencilOperationFail);
  97157. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97158. engine.setStencilFunctionReference(previousStencilReference);
  97159. };
  97160. /**
  97161. * Returns true if the layer contains information to display, otherwise false.
  97162. */
  97163. HighlightLayer.prototype.shouldRender = function () {
  97164. if (_super.prototype.shouldRender.call(this)) {
  97165. return this._meshes ? true : false;
  97166. }
  97167. return false;
  97168. };
  97169. /**
  97170. * Returns true if the mesh should render, otherwise false.
  97171. * @param mesh The mesh to render
  97172. * @returns true if it should render otherwise false
  97173. */
  97174. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97175. // Excluded Mesh
  97176. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97177. return false;
  97178. }
  97179. ;
  97180. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97181. return false;
  97182. }
  97183. return true;
  97184. };
  97185. /**
  97186. * Sets the required values for both the emissive texture and and the main color.
  97187. */
  97188. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97189. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97190. if (highlightLayerMesh) {
  97191. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97192. }
  97193. else {
  97194. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97195. }
  97196. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97197. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97198. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97199. }
  97200. else {
  97201. this._emissiveTextureAndColor.texture = null;
  97202. }
  97203. };
  97204. /**
  97205. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97206. * @param mesh The mesh to exclude from the highlight layer
  97207. */
  97208. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97209. if (!this._excludedMeshes) {
  97210. return;
  97211. }
  97212. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97213. if (!meshExcluded) {
  97214. this._excludedMeshes[mesh.uniqueId] = {
  97215. mesh: mesh,
  97216. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97217. mesh.getEngine().setStencilBuffer(false);
  97218. }),
  97219. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97220. mesh.getEngine().setStencilBuffer(true);
  97221. }),
  97222. };
  97223. }
  97224. };
  97225. /**
  97226. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97227. * @param mesh The mesh to highlight
  97228. */
  97229. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97230. if (!this._excludedMeshes) {
  97231. return;
  97232. }
  97233. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97234. if (meshExcluded) {
  97235. if (meshExcluded.beforeRender) {
  97236. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97237. }
  97238. if (meshExcluded.afterRender) {
  97239. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97240. }
  97241. }
  97242. this._excludedMeshes[mesh.uniqueId] = null;
  97243. };
  97244. /**
  97245. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97246. * @param mesh mesh to test
  97247. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97248. */
  97249. HighlightLayer.prototype.hasMesh = function (mesh) {
  97250. if (!this._meshes) {
  97251. return false;
  97252. }
  97253. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97254. return false;
  97255. }
  97256. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97257. };
  97258. /**
  97259. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97260. * @param mesh The mesh to highlight
  97261. * @param color The color of the highlight
  97262. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97263. */
  97264. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97265. var _this = this;
  97266. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97267. if (!this._meshes) {
  97268. return;
  97269. }
  97270. var meshHighlight = this._meshes[mesh.uniqueId];
  97271. if (meshHighlight) {
  97272. meshHighlight.color = color;
  97273. }
  97274. else {
  97275. this._meshes[mesh.uniqueId] = {
  97276. mesh: mesh,
  97277. color: color,
  97278. // Lambda required for capture due to Observable this context
  97279. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97280. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97281. _this._defaultStencilReference(mesh);
  97282. }
  97283. else {
  97284. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97285. }
  97286. }),
  97287. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97288. glowEmissiveOnly: glowEmissiveOnly
  97289. };
  97290. mesh.onDisposeObservable.add(function () {
  97291. _this._disposeMesh(mesh);
  97292. });
  97293. }
  97294. this._shouldRender = true;
  97295. };
  97296. /**
  97297. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97298. * @param mesh The mesh to highlight
  97299. */
  97300. HighlightLayer.prototype.removeMesh = function (mesh) {
  97301. if (!this._meshes) {
  97302. return;
  97303. }
  97304. var meshHighlight = this._meshes[mesh.uniqueId];
  97305. if (meshHighlight) {
  97306. if (meshHighlight.observerHighlight) {
  97307. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97308. }
  97309. if (meshHighlight.observerDefault) {
  97310. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97311. }
  97312. delete this._meshes[mesh.uniqueId];
  97313. }
  97314. this._shouldRender = false;
  97315. for (var meshHighlightToCheck in this._meshes) {
  97316. if (this._meshes[meshHighlightToCheck]) {
  97317. this._shouldRender = true;
  97318. break;
  97319. }
  97320. }
  97321. };
  97322. /**
  97323. * Force the stencil to the normal expected value for none glowing parts
  97324. */
  97325. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97326. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97327. };
  97328. /**
  97329. * Free any resources and references associated to a mesh.
  97330. * Internal use
  97331. * @param mesh The mesh to free.
  97332. */
  97333. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97334. this.removeMesh(mesh);
  97335. this.removeExcludedMesh(mesh);
  97336. };
  97337. /**
  97338. * Dispose the highlight layer and free resources.
  97339. */
  97340. HighlightLayer.prototype.dispose = function () {
  97341. if (this._meshes) {
  97342. // Clean mesh references
  97343. for (var id in this._meshes) {
  97344. var meshHighlight = this._meshes[id];
  97345. if (meshHighlight && meshHighlight.mesh) {
  97346. if (meshHighlight.observerHighlight) {
  97347. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97348. }
  97349. if (meshHighlight.observerDefault) {
  97350. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97351. }
  97352. }
  97353. }
  97354. this._meshes = null;
  97355. }
  97356. if (this._excludedMeshes) {
  97357. for (var id in this._excludedMeshes) {
  97358. var meshHighlight = this._excludedMeshes[id];
  97359. if (meshHighlight) {
  97360. if (meshHighlight.beforeRender) {
  97361. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97362. }
  97363. if (meshHighlight.afterRender) {
  97364. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97365. }
  97366. }
  97367. }
  97368. this._excludedMeshes = null;
  97369. }
  97370. _super.prototype.dispose.call(this);
  97371. };
  97372. /**
  97373. * Gets the class name of the effect layer
  97374. * @returns the string with the class name of the effect layer
  97375. */
  97376. HighlightLayer.prototype.getClassName = function () {
  97377. return "HighlightLayer";
  97378. };
  97379. /**
  97380. * Serializes this Highlight layer
  97381. * @returns a serialized Highlight layer object
  97382. */
  97383. HighlightLayer.prototype.serialize = function () {
  97384. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97385. serializationObject.customType = "BABYLON.HighlightLayer";
  97386. // Highlighted meshes
  97387. serializationObject.meshes = [];
  97388. if (this._meshes) {
  97389. for (var m in this._meshes) {
  97390. var mesh = this._meshes[m];
  97391. if (mesh) {
  97392. serializationObject.meshes.push({
  97393. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97394. color: mesh.color.asArray(),
  97395. meshId: mesh.mesh.id
  97396. });
  97397. }
  97398. }
  97399. }
  97400. // Excluded meshes
  97401. serializationObject.excludedMeshes = [];
  97402. if (this._excludedMeshes) {
  97403. for (var e in this._excludedMeshes) {
  97404. var excludedMesh = this._excludedMeshes[e];
  97405. if (excludedMesh) {
  97406. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97407. }
  97408. }
  97409. }
  97410. return serializationObject;
  97411. };
  97412. /**
  97413. * Creates a Highlight layer from parsed Highlight layer data
  97414. * @param parsedHightlightLayer defines the Highlight layer data
  97415. * @param scene defines the current scene
  97416. * @param rootUrl defines the root URL containing the Highlight layer information
  97417. * @returns a parsed Highlight layer
  97418. */
  97419. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97420. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97421. var index;
  97422. // Excluded meshes
  97423. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97424. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97425. if (mesh) {
  97426. hl.addExcludedMesh(mesh);
  97427. }
  97428. }
  97429. // Included meshes
  97430. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97431. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97432. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97433. if (mesh) {
  97434. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97435. }
  97436. }
  97437. return hl;
  97438. };
  97439. /**
  97440. * Effect Name of the highlight layer.
  97441. */
  97442. HighlightLayer.EffectName = "HighlightLayer";
  97443. /**
  97444. * The neutral color used during the preparation of the glow effect.
  97445. * This is black by default as the blend operation is a blend operation.
  97446. */
  97447. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97448. /**
  97449. * Stencil value used for glowing meshes.
  97450. */
  97451. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97452. /**
  97453. * Stencil value used for the other meshes in the scene.
  97454. */
  97455. HighlightLayer.NormalMeshStencilReference = 0x01;
  97456. __decorate([
  97457. BABYLON.serialize()
  97458. ], HighlightLayer.prototype, "innerGlow", void 0);
  97459. __decorate([
  97460. BABYLON.serialize()
  97461. ], HighlightLayer.prototype, "outerGlow", void 0);
  97462. __decorate([
  97463. BABYLON.serialize()
  97464. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97465. __decorate([
  97466. BABYLON.serialize()
  97467. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97468. __decorate([
  97469. BABYLON.serialize("options")
  97470. ], HighlightLayer.prototype, "_options", void 0);
  97471. return HighlightLayer;
  97472. }(BABYLON.EffectLayer));
  97473. BABYLON.HighlightLayer = HighlightLayer;
  97474. })(BABYLON || (BABYLON = {}));
  97475. //# sourceMappingURL=babylon.highlightLayer.js.map
  97476. var BABYLON;
  97477. (function (BABYLON) {
  97478. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97479. for (var index = 0; index < this.effectLayers.length; index++) {
  97480. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97481. return this.effectLayers[index];
  97482. }
  97483. }
  97484. return null;
  97485. };
  97486. /**
  97487. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97488. *
  97489. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97490. * glowy meshes to your scene.
  97491. *
  97492. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97493. */
  97494. var GlowLayer = /** @class */ (function (_super) {
  97495. __extends(GlowLayer, _super);
  97496. /**
  97497. * Instantiates a new glow Layer and references it to the scene.
  97498. * @param name The name of the layer
  97499. * @param scene The scene to use the layer in
  97500. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97501. */
  97502. function GlowLayer(name, scene, options) {
  97503. var _this = _super.call(this, name, scene) || this;
  97504. _this._intensity = 1.0;
  97505. _this._includedOnlyMeshes = [];
  97506. _this._excludedMeshes = [];
  97507. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97508. // Adapt options
  97509. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97510. // Initialize the layer
  97511. _this._init({
  97512. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97513. camera: _this._options.camera,
  97514. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97515. mainTextureRatio: _this._options.mainTextureRatio,
  97516. renderingGroupId: _this._options.renderingGroupId
  97517. });
  97518. return _this;
  97519. }
  97520. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97521. /**
  97522. * Gets the kernel size of the blur.
  97523. */
  97524. get: function () {
  97525. return this._horizontalBlurPostprocess1.kernel;
  97526. },
  97527. /**
  97528. * Sets the kernel size of the blur.
  97529. */
  97530. set: function (value) {
  97531. this._horizontalBlurPostprocess1.kernel = value;
  97532. this._verticalBlurPostprocess1.kernel = value;
  97533. this._horizontalBlurPostprocess2.kernel = value;
  97534. this._verticalBlurPostprocess2.kernel = value;
  97535. },
  97536. enumerable: true,
  97537. configurable: true
  97538. });
  97539. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97540. /**
  97541. * Gets the glow intensity.
  97542. */
  97543. get: function () {
  97544. return this._intensity;
  97545. },
  97546. /**
  97547. * Sets the glow intensity.
  97548. */
  97549. set: function (value) {
  97550. this._intensity = value;
  97551. },
  97552. enumerable: true,
  97553. configurable: true
  97554. });
  97555. /**
  97556. * Get the effect name of the layer.
  97557. * @return The effect name
  97558. */
  97559. GlowLayer.prototype.getEffectName = function () {
  97560. return GlowLayer.EffectName;
  97561. };
  97562. /**
  97563. * Create the merge effect. This is the shader use to blit the information back
  97564. * to the main canvas at the end of the scene rendering.
  97565. */
  97566. GlowLayer.prototype._createMergeEffect = function () {
  97567. // Effect
  97568. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97569. };
  97570. /**
  97571. * Creates the render target textures and post processes used in the glow layer.
  97572. */
  97573. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97574. var _this = this;
  97575. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97576. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97577. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97578. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97579. var textureType = 0;
  97580. if (this._engine.getCaps().textureHalfFloatRender) {
  97581. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97582. }
  97583. else {
  97584. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97585. }
  97586. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97587. width: blurTextureWidth,
  97588. height: blurTextureHeight
  97589. }, this._scene, false, true, textureType);
  97590. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97591. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97592. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97593. this._blurTexture1.renderParticles = false;
  97594. this._blurTexture1.ignoreCameraViewport = true;
  97595. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97596. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97597. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97598. width: blurTextureWidth2,
  97599. height: blurTextureHeight2
  97600. }, this._scene, false, true, textureType);
  97601. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97602. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97603. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97604. this._blurTexture2.renderParticles = false;
  97605. this._blurTexture2.ignoreCameraViewport = true;
  97606. this._textures = [this._blurTexture1, this._blurTexture2];
  97607. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97608. width: blurTextureWidth,
  97609. height: blurTextureHeight
  97610. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97611. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97612. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97613. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97614. effect.setTexture("textureSampler", _this._mainTexture);
  97615. });
  97616. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97617. width: blurTextureWidth,
  97618. height: blurTextureHeight
  97619. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97620. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97621. width: blurTextureWidth2,
  97622. height: blurTextureHeight2
  97623. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97624. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97625. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97626. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97627. effect.setTexture("textureSampler", _this._blurTexture1);
  97628. });
  97629. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97630. width: blurTextureWidth2,
  97631. height: blurTextureHeight2
  97632. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97633. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97634. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97635. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97636. this._mainTexture.samples = this._options.mainTextureSamples;
  97637. this._mainTexture.onAfterUnbindObservable.add(function () {
  97638. var internalTexture = _this._blurTexture1.getInternalTexture();
  97639. if (internalTexture) {
  97640. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97641. internalTexture = _this._blurTexture2.getInternalTexture();
  97642. if (internalTexture) {
  97643. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97644. }
  97645. }
  97646. });
  97647. // Prevent autoClear.
  97648. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97649. };
  97650. /**
  97651. * Checks for the readiness of the element composing the layer.
  97652. * @param subMesh the mesh to check for
  97653. * @param useInstances specify wether or not to use instances to render the mesh
  97654. * @param emissiveTexture the associated emissive texture used to generate the glow
  97655. * @return true if ready otherwise, false
  97656. */
  97657. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97658. var material = subMesh.getMaterial();
  97659. var mesh = subMesh.getRenderingMesh();
  97660. if (!material || !mesh) {
  97661. return false;
  97662. }
  97663. var emissiveTexture = material.emissiveTexture;
  97664. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97665. };
  97666. /**
  97667. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97668. */
  97669. GlowLayer.prototype.needStencil = function () {
  97670. return false;
  97671. };
  97672. /**
  97673. * Implementation specific of rendering the generating effect on the main canvas.
  97674. * @param effect The effect used to render through
  97675. */
  97676. GlowLayer.prototype._internalRender = function (effect) {
  97677. // Texture
  97678. effect.setTexture("textureSampler", this._blurTexture1);
  97679. effect.setTexture("textureSampler2", this._blurTexture2);
  97680. effect.setFloat("offset", this._intensity);
  97681. // Cache
  97682. var engine = this._engine;
  97683. var previousStencilBuffer = engine.getStencilBuffer();
  97684. // Draw order
  97685. engine.setStencilBuffer(false);
  97686. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97687. // Draw order
  97688. engine.setStencilBuffer(previousStencilBuffer);
  97689. };
  97690. /**
  97691. * Sets the required values for both the emissive texture and and the main color.
  97692. */
  97693. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97694. var textureLevel = 1.0;
  97695. if (this.customEmissiveTextureSelector) {
  97696. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97697. }
  97698. else {
  97699. if (material) {
  97700. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97701. if (this._emissiveTextureAndColor.texture) {
  97702. textureLevel = this._emissiveTextureAndColor.texture.level;
  97703. }
  97704. }
  97705. else {
  97706. this._emissiveTextureAndColor.texture = null;
  97707. }
  97708. }
  97709. if (this.customEmissiveColorSelector) {
  97710. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97711. }
  97712. else {
  97713. if (material.emissiveColor) {
  97714. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97715. }
  97716. else {
  97717. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97718. }
  97719. }
  97720. };
  97721. /**
  97722. * Returns true if the mesh should render, otherwise false.
  97723. * @param mesh The mesh to render
  97724. * @returns true if it should render otherwise false
  97725. */
  97726. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97727. return this.hasMesh(mesh);
  97728. };
  97729. /**
  97730. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97731. * @param mesh The mesh to exclude from the glow layer
  97732. */
  97733. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97734. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97735. this._excludedMeshes.push(mesh.uniqueId);
  97736. }
  97737. };
  97738. /**
  97739. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97740. * @param mesh The mesh to remove
  97741. */
  97742. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97743. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97744. if (index !== -1) {
  97745. this._excludedMeshes.splice(index, 1);
  97746. }
  97747. };
  97748. /**
  97749. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97750. * @param mesh The mesh to include in the glow layer
  97751. */
  97752. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97753. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97754. this._includedOnlyMeshes.push(mesh.uniqueId);
  97755. }
  97756. };
  97757. /**
  97758. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97759. * @param mesh The mesh to remove
  97760. */
  97761. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97762. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97763. if (index !== -1) {
  97764. this._includedOnlyMeshes.splice(index, 1);
  97765. }
  97766. };
  97767. /**
  97768. * Determine if a given mesh will be used in the glow layer
  97769. * @param mesh The mesh to test
  97770. * @returns true if the mesh will be highlighted by the current glow layer
  97771. */
  97772. GlowLayer.prototype.hasMesh = function (mesh) {
  97773. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97774. return false;
  97775. }
  97776. // Included Mesh
  97777. if (this._includedOnlyMeshes.length) {
  97778. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97779. }
  97780. ;
  97781. // Excluded Mesh
  97782. if (this._excludedMeshes.length) {
  97783. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97784. }
  97785. ;
  97786. return true;
  97787. };
  97788. /**
  97789. * Free any resources and references associated to a mesh.
  97790. * Internal use
  97791. * @param mesh The mesh to free.
  97792. */
  97793. GlowLayer.prototype._disposeMesh = function (mesh) {
  97794. this.removeIncludedOnlyMesh(mesh);
  97795. this.removeExcludedMesh(mesh);
  97796. };
  97797. /**
  97798. * Gets the class name of the effect layer
  97799. * @returns the string with the class name of the effect layer
  97800. */
  97801. GlowLayer.prototype.getClassName = function () {
  97802. return "GlowLayer";
  97803. };
  97804. /**
  97805. * Serializes this glow layer
  97806. * @returns a serialized glow layer object
  97807. */
  97808. GlowLayer.prototype.serialize = function () {
  97809. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97810. serializationObject.customType = "BABYLON.GlowLayer";
  97811. var index;
  97812. // Included meshes
  97813. serializationObject.includedMeshes = [];
  97814. if (this._includedOnlyMeshes.length) {
  97815. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97816. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97817. if (mesh) {
  97818. serializationObject.includedMeshes.push(mesh.id);
  97819. }
  97820. }
  97821. }
  97822. // Excluded meshes
  97823. serializationObject.excludedMeshes = [];
  97824. if (this._excludedMeshes.length) {
  97825. for (index = 0; index < this._excludedMeshes.length; index++) {
  97826. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97827. if (mesh) {
  97828. serializationObject.excludedMeshes.push(mesh.id);
  97829. }
  97830. }
  97831. }
  97832. return serializationObject;
  97833. };
  97834. /**
  97835. * Creates a Glow Layer from parsed glow layer data
  97836. * @param parsedGlowLayer defines glow layer data
  97837. * @param scene defines the current scene
  97838. * @param rootUrl defines the root URL containing the glow layer information
  97839. * @returns a parsed Glow Layer
  97840. */
  97841. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97842. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97843. var index;
  97844. // Excluded meshes
  97845. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97846. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97847. if (mesh) {
  97848. gl.addExcludedMesh(mesh);
  97849. }
  97850. }
  97851. // Included meshes
  97852. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97853. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97854. if (mesh) {
  97855. gl.addIncludedOnlyMesh(mesh);
  97856. }
  97857. }
  97858. return gl;
  97859. };
  97860. /**
  97861. * Effect Name of the layer.
  97862. */
  97863. GlowLayer.EffectName = "GlowLayer";
  97864. /**
  97865. * The default blur kernel size used for the glow.
  97866. */
  97867. GlowLayer.DefaultBlurKernelSize = 32;
  97868. /**
  97869. * The default texture size ratio used for the glow.
  97870. */
  97871. GlowLayer.DefaultTextureRatio = 0.5;
  97872. __decorate([
  97873. BABYLON.serialize()
  97874. ], GlowLayer.prototype, "blurKernelSize", null);
  97875. __decorate([
  97876. BABYLON.serialize()
  97877. ], GlowLayer.prototype, "intensity", null);
  97878. __decorate([
  97879. BABYLON.serialize("options")
  97880. ], GlowLayer.prototype, "_options", void 0);
  97881. return GlowLayer;
  97882. }(BABYLON.EffectLayer));
  97883. BABYLON.GlowLayer = GlowLayer;
  97884. })(BABYLON || (BABYLON = {}));
  97885. //# sourceMappingURL=babylon.glowLayer.js.map
  97886. var BABYLON;
  97887. (function (BABYLON) {
  97888. /**
  97889. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97890. */
  97891. var AssetTaskState;
  97892. (function (AssetTaskState) {
  97893. /**
  97894. * Initialization
  97895. */
  97896. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97897. /**
  97898. * Running
  97899. */
  97900. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97901. /**
  97902. * Done
  97903. */
  97904. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97905. /**
  97906. * Error
  97907. */
  97908. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97909. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97910. /**
  97911. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97912. */
  97913. var AbstractAssetTask = /** @class */ (function () {
  97914. /**
  97915. * Creates a new {BABYLON.AssetsManager}
  97916. * @param name defines the name of the task
  97917. */
  97918. function AbstractAssetTask(
  97919. /**
  97920. * Task name
  97921. */ name) {
  97922. this.name = name;
  97923. this._isCompleted = false;
  97924. this._taskState = AssetTaskState.INIT;
  97925. }
  97926. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97927. /**
  97928. * Get if the task is completed
  97929. */
  97930. get: function () {
  97931. return this._isCompleted;
  97932. },
  97933. enumerable: true,
  97934. configurable: true
  97935. });
  97936. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97937. /**
  97938. * Gets the current state of the task
  97939. */
  97940. get: function () {
  97941. return this._taskState;
  97942. },
  97943. enumerable: true,
  97944. configurable: true
  97945. });
  97946. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97947. /**
  97948. * Gets the current error object (if task is in error)
  97949. */
  97950. get: function () {
  97951. return this._errorObject;
  97952. },
  97953. enumerable: true,
  97954. configurable: true
  97955. });
  97956. /**
  97957. * Internal only
  97958. * @hidden
  97959. */
  97960. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97961. if (this._errorObject) {
  97962. return;
  97963. }
  97964. this._errorObject = {
  97965. message: message,
  97966. exception: exception
  97967. };
  97968. };
  97969. /**
  97970. * Execute the current task
  97971. * @param scene defines the scene where you want your assets to be loaded
  97972. * @param onSuccess is a callback called when the task is successfully executed
  97973. * @param onError is a callback called if an error occurs
  97974. */
  97975. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97976. var _this = this;
  97977. this._taskState = AssetTaskState.RUNNING;
  97978. this.runTask(scene, function () {
  97979. _this.onDoneCallback(onSuccess, onError);
  97980. }, function (msg, exception) {
  97981. _this.onErrorCallback(onError, msg, exception);
  97982. });
  97983. };
  97984. /**
  97985. * Execute the current task
  97986. * @param scene defines the scene where you want your assets to be loaded
  97987. * @param onSuccess is a callback called when the task is successfully executed
  97988. * @param onError is a callback called if an error occurs
  97989. */
  97990. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97991. throw new Error("runTask is not implemented");
  97992. };
  97993. /**
  97994. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97995. * This can be used with failed tasks that have the reason for failure fixed.
  97996. */
  97997. AbstractAssetTask.prototype.reset = function () {
  97998. this._taskState = AssetTaskState.INIT;
  97999. };
  98000. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98001. this._taskState = AssetTaskState.ERROR;
  98002. this._errorObject = {
  98003. message: message,
  98004. exception: exception
  98005. };
  98006. if (this.onError) {
  98007. this.onError(this, message, exception);
  98008. }
  98009. onError();
  98010. };
  98011. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98012. try {
  98013. this._taskState = AssetTaskState.DONE;
  98014. this._isCompleted = true;
  98015. if (this.onSuccess) {
  98016. this.onSuccess(this);
  98017. }
  98018. onSuccess();
  98019. }
  98020. catch (e) {
  98021. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98022. }
  98023. };
  98024. return AbstractAssetTask;
  98025. }());
  98026. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98027. /**
  98028. * Class used to share progress information about assets loading
  98029. */
  98030. var AssetsProgressEvent = /** @class */ (function () {
  98031. /**
  98032. * Creates a {BABYLON.AssetsProgressEvent}
  98033. * @param remainingCount defines the number of remaining tasks to process
  98034. * @param totalCount defines the total number of tasks
  98035. * @param task defines the task that was just processed
  98036. */
  98037. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98038. this.remainingCount = remainingCount;
  98039. this.totalCount = totalCount;
  98040. this.task = task;
  98041. }
  98042. return AssetsProgressEvent;
  98043. }());
  98044. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98045. /**
  98046. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98047. */
  98048. var MeshAssetTask = /** @class */ (function (_super) {
  98049. __extends(MeshAssetTask, _super);
  98050. /**
  98051. * Creates a new {BABYLON.MeshAssetTask}
  98052. * @param name defines the name of the task
  98053. * @param meshesNames defines the list of mesh's names you want to load
  98054. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98055. * @param sceneFilename defines the filename of the scene to load from
  98056. */
  98057. function MeshAssetTask(
  98058. /**
  98059. * Defines the name of the task
  98060. */
  98061. name,
  98062. /**
  98063. * Defines the list of mesh's names you want to load
  98064. */
  98065. meshesNames,
  98066. /**
  98067. * Defines the root url to use as a base to load your meshes and associated resources
  98068. */
  98069. rootUrl,
  98070. /**
  98071. * Defines the filename of the scene to load from
  98072. */
  98073. sceneFilename) {
  98074. var _this = _super.call(this, name) || this;
  98075. _this.name = name;
  98076. _this.meshesNames = meshesNames;
  98077. _this.rootUrl = rootUrl;
  98078. _this.sceneFilename = sceneFilename;
  98079. return _this;
  98080. }
  98081. /**
  98082. * Execute the current task
  98083. * @param scene defines the scene where you want your assets to be loaded
  98084. * @param onSuccess is a callback called when the task is successfully executed
  98085. * @param onError is a callback called if an error occurs
  98086. */
  98087. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98088. var _this = this;
  98089. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98090. _this.loadedMeshes = meshes;
  98091. _this.loadedParticleSystems = particleSystems;
  98092. _this.loadedSkeletons = skeletons;
  98093. onSuccess();
  98094. }, null, function (scene, message, exception) {
  98095. onError(message, exception);
  98096. });
  98097. };
  98098. return MeshAssetTask;
  98099. }(AbstractAssetTask));
  98100. BABYLON.MeshAssetTask = MeshAssetTask;
  98101. /**
  98102. * Define a task used by {BABYLON.AssetsManager} to load text content
  98103. */
  98104. var TextFileAssetTask = /** @class */ (function (_super) {
  98105. __extends(TextFileAssetTask, _super);
  98106. /**
  98107. * Creates a new TextFileAssetTask object
  98108. * @param name defines the name of the task
  98109. * @param url defines the location of the file to load
  98110. */
  98111. function TextFileAssetTask(
  98112. /**
  98113. * Defines the name of the task
  98114. */
  98115. name,
  98116. /**
  98117. * Defines the location of the file to load
  98118. */
  98119. url) {
  98120. var _this = _super.call(this, name) || this;
  98121. _this.name = name;
  98122. _this.url = url;
  98123. return _this;
  98124. }
  98125. /**
  98126. * Execute the current task
  98127. * @param scene defines the scene where you want your assets to be loaded
  98128. * @param onSuccess is a callback called when the task is successfully executed
  98129. * @param onError is a callback called if an error occurs
  98130. */
  98131. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98132. var _this = this;
  98133. scene._loadFile(this.url, function (data) {
  98134. _this.text = data;
  98135. onSuccess();
  98136. }, undefined, false, false, function (request, exception) {
  98137. if (request) {
  98138. onError(request.status + " " + request.statusText, exception);
  98139. }
  98140. });
  98141. };
  98142. return TextFileAssetTask;
  98143. }(AbstractAssetTask));
  98144. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98145. /**
  98146. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98147. */
  98148. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98149. __extends(BinaryFileAssetTask, _super);
  98150. /**
  98151. * Creates a new BinaryFileAssetTask object
  98152. * @param name defines the name of the new task
  98153. * @param url defines the location of the file to load
  98154. */
  98155. function BinaryFileAssetTask(
  98156. /**
  98157. * Defines the name of the task
  98158. */
  98159. name,
  98160. /**
  98161. * Defines the location of the file to load
  98162. */
  98163. url) {
  98164. var _this = _super.call(this, name) || this;
  98165. _this.name = name;
  98166. _this.url = url;
  98167. return _this;
  98168. }
  98169. /**
  98170. * Execute the current task
  98171. * @param scene defines the scene where you want your assets to be loaded
  98172. * @param onSuccess is a callback called when the task is successfully executed
  98173. * @param onError is a callback called if an error occurs
  98174. */
  98175. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98176. var _this = this;
  98177. scene._loadFile(this.url, function (data) {
  98178. _this.data = data;
  98179. onSuccess();
  98180. }, undefined, true, true, function (request, exception) {
  98181. if (request) {
  98182. onError(request.status + " " + request.statusText, exception);
  98183. }
  98184. });
  98185. };
  98186. return BinaryFileAssetTask;
  98187. }(AbstractAssetTask));
  98188. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98189. /**
  98190. * Define a task used by {BABYLON.AssetsManager} to load images
  98191. */
  98192. var ImageAssetTask = /** @class */ (function (_super) {
  98193. __extends(ImageAssetTask, _super);
  98194. /**
  98195. * Creates a new ImageAssetTask
  98196. * @param name defines the name of the task
  98197. * @param url defines the location of the image to load
  98198. */
  98199. function ImageAssetTask(
  98200. /**
  98201. * Defines the name of the task
  98202. */
  98203. name,
  98204. /**
  98205. * Defines the location of the image to load
  98206. */
  98207. url) {
  98208. var _this = _super.call(this, name) || this;
  98209. _this.name = name;
  98210. _this.url = url;
  98211. return _this;
  98212. }
  98213. /**
  98214. * Execute the current task
  98215. * @param scene defines the scene where you want your assets to be loaded
  98216. * @param onSuccess is a callback called when the task is successfully executed
  98217. * @param onError is a callback called if an error occurs
  98218. */
  98219. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98220. var _this = this;
  98221. var img = new Image();
  98222. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98223. img.onload = function () {
  98224. _this.image = img;
  98225. onSuccess();
  98226. };
  98227. img.onerror = function (err) {
  98228. onError("Error loading image", err);
  98229. };
  98230. img.src = this.url;
  98231. };
  98232. return ImageAssetTask;
  98233. }(AbstractAssetTask));
  98234. BABYLON.ImageAssetTask = ImageAssetTask;
  98235. /**
  98236. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98237. */
  98238. var TextureAssetTask = /** @class */ (function (_super) {
  98239. __extends(TextureAssetTask, _super);
  98240. /**
  98241. * Creates a new TextureAssetTask object
  98242. * @param name defines the name of the task
  98243. * @param url defines the location of the file to load
  98244. * @param noMipmap defines if mipmap should not be generated (default is false)
  98245. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98246. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98247. */
  98248. function TextureAssetTask(
  98249. /**
  98250. * Defines the name of the task
  98251. */
  98252. name,
  98253. /**
  98254. * Defines the location of the file to load
  98255. */
  98256. url,
  98257. /**
  98258. * Defines if mipmap should not be generated (default is false)
  98259. */
  98260. noMipmap,
  98261. /**
  98262. * Defines if texture must be inverted on Y axis (default is false)
  98263. */
  98264. invertY,
  98265. /**
  98266. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98267. */
  98268. samplingMode) {
  98269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98270. var _this = _super.call(this, name) || this;
  98271. _this.name = name;
  98272. _this.url = url;
  98273. _this.noMipmap = noMipmap;
  98274. _this.invertY = invertY;
  98275. _this.samplingMode = samplingMode;
  98276. return _this;
  98277. }
  98278. /**
  98279. * Execute the current task
  98280. * @param scene defines the scene where you want your assets to be loaded
  98281. * @param onSuccess is a callback called when the task is successfully executed
  98282. * @param onError is a callback called if an error occurs
  98283. */
  98284. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98285. var onload = function () {
  98286. onSuccess();
  98287. };
  98288. var onerror = function (message, exception) {
  98289. onError(message, exception);
  98290. };
  98291. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98292. };
  98293. return TextureAssetTask;
  98294. }(AbstractAssetTask));
  98295. BABYLON.TextureAssetTask = TextureAssetTask;
  98296. /**
  98297. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98298. */
  98299. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98300. __extends(CubeTextureAssetTask, _super);
  98301. /**
  98302. * Creates a new CubeTextureAssetTask
  98303. * @param name defines the name of the task
  98304. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98305. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98306. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98307. * @param files defines the explicit list of files (undefined by default)
  98308. */
  98309. function CubeTextureAssetTask(
  98310. /**
  98311. * Defines the name of the task
  98312. */
  98313. name,
  98314. /**
  98315. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98316. */
  98317. url,
  98318. /**
  98319. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98320. */
  98321. extensions,
  98322. /**
  98323. * Defines if mipmaps should not be generated (default is false)
  98324. */
  98325. noMipmap,
  98326. /**
  98327. * Defines the explicit list of files (undefined by default)
  98328. */
  98329. files) {
  98330. var _this = _super.call(this, name) || this;
  98331. _this.name = name;
  98332. _this.url = url;
  98333. _this.extensions = extensions;
  98334. _this.noMipmap = noMipmap;
  98335. _this.files = files;
  98336. return _this;
  98337. }
  98338. /**
  98339. * Execute the current task
  98340. * @param scene defines the scene where you want your assets to be loaded
  98341. * @param onSuccess is a callback called when the task is successfully executed
  98342. * @param onError is a callback called if an error occurs
  98343. */
  98344. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98345. var onload = function () {
  98346. onSuccess();
  98347. };
  98348. var onerror = function (message, exception) {
  98349. onError(message, exception);
  98350. };
  98351. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98352. };
  98353. return CubeTextureAssetTask;
  98354. }(AbstractAssetTask));
  98355. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98356. /**
  98357. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98358. */
  98359. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98360. __extends(HDRCubeTextureAssetTask, _super);
  98361. /**
  98362. * Creates a new HDRCubeTextureAssetTask object
  98363. * @param name defines the name of the task
  98364. * @param url defines the location of the file to load
  98365. * @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.
  98366. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98367. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98368. * @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)
  98369. * @param reserved Internal use only
  98370. */
  98371. function HDRCubeTextureAssetTask(
  98372. /**
  98373. * Defines the name of the task
  98374. */
  98375. name,
  98376. /**
  98377. * Defines the location of the file to load
  98378. */
  98379. url,
  98380. /**
  98381. * Defines the desired size (the more it increases the longer the generation will be)
  98382. */
  98383. size,
  98384. /**
  98385. * Defines if mipmaps should not be generated (default is false)
  98386. */
  98387. noMipmap,
  98388. /**
  98389. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98390. */
  98391. generateHarmonics,
  98392. /**
  98393. * 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)
  98394. */
  98395. gammaSpace,
  98396. /**
  98397. * Internal Use Only
  98398. */
  98399. reserved) {
  98400. if (noMipmap === void 0) { noMipmap = false; }
  98401. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98402. if (gammaSpace === void 0) { gammaSpace = false; }
  98403. if (reserved === void 0) { reserved = false; }
  98404. var _this = _super.call(this, name) || this;
  98405. _this.name = name;
  98406. _this.url = url;
  98407. _this.size = size;
  98408. _this.noMipmap = noMipmap;
  98409. _this.generateHarmonics = generateHarmonics;
  98410. _this.gammaSpace = gammaSpace;
  98411. _this.reserved = reserved;
  98412. return _this;
  98413. }
  98414. /**
  98415. * Execute the current task
  98416. * @param scene defines the scene where you want your assets to be loaded
  98417. * @param onSuccess is a callback called when the task is successfully executed
  98418. * @param onError is a callback called if an error occurs
  98419. */
  98420. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98421. var onload = function () {
  98422. onSuccess();
  98423. };
  98424. var onerror = function (message, exception) {
  98425. onError(message, exception);
  98426. };
  98427. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98428. };
  98429. return HDRCubeTextureAssetTask;
  98430. }(AbstractAssetTask));
  98431. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98432. /**
  98433. * This class can be used to easily import assets into a scene
  98434. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98435. */
  98436. var AssetsManager = /** @class */ (function () {
  98437. /**
  98438. * Creates a new AssetsManager
  98439. * @param scene defines the scene to work on
  98440. */
  98441. function AssetsManager(scene) {
  98442. this._isLoading = false;
  98443. this._tasks = new Array();
  98444. this._waitingTasksCount = 0;
  98445. this._totalTasksCount = 0;
  98446. /**
  98447. * Observable called when all tasks are processed
  98448. */
  98449. this.onTaskSuccessObservable = new BABYLON.Observable();
  98450. /**
  98451. * Observable called when a task had an error
  98452. */
  98453. this.onTaskErrorObservable = new BABYLON.Observable();
  98454. /**
  98455. * Observable called when a task is successful
  98456. */
  98457. this.onTasksDoneObservable = new BABYLON.Observable();
  98458. /**
  98459. * Observable called when a task is done (whatever the result is)
  98460. */
  98461. this.onProgressObservable = new BABYLON.Observable();
  98462. /**
  98463. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98464. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98465. */
  98466. this.useDefaultLoadingScreen = true;
  98467. this._scene = scene;
  98468. }
  98469. /**
  98470. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98471. * @param taskName defines the name of the new task
  98472. * @param meshesNames defines the name of meshes to load
  98473. * @param rootUrl defines the root url to use to locate files
  98474. * @param sceneFilename defines the filename of the scene file
  98475. * @returns a new {BABYLON.MeshAssetTask} object
  98476. */
  98477. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98478. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98479. this._tasks.push(task);
  98480. return task;
  98481. };
  98482. /**
  98483. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98484. * @param taskName defines the name of the new task
  98485. * @param url defines the url of the file to load
  98486. * @returns a new {BABYLON.TextFileAssetTask} object
  98487. */
  98488. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98489. var task = new TextFileAssetTask(taskName, url);
  98490. this._tasks.push(task);
  98491. return task;
  98492. };
  98493. /**
  98494. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98495. * @param taskName defines the name of the new task
  98496. * @param url defines the url of the file to load
  98497. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98498. */
  98499. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98500. var task = new BinaryFileAssetTask(taskName, url);
  98501. this._tasks.push(task);
  98502. return task;
  98503. };
  98504. /**
  98505. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98506. * @param taskName defines the name of the new task
  98507. * @param url defines the url of the file to load
  98508. * @returns a new {BABYLON.ImageAssetTask} object
  98509. */
  98510. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98511. var task = new ImageAssetTask(taskName, url);
  98512. this._tasks.push(task);
  98513. return task;
  98514. };
  98515. /**
  98516. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98517. * @param taskName defines the name of the new task
  98518. * @param url defines the url of the file to load
  98519. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98520. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98521. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98522. * @returns a new {BABYLON.TextureAssetTask} object
  98523. */
  98524. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98526. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98527. this._tasks.push(task);
  98528. return task;
  98529. };
  98530. /**
  98531. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98532. * @param taskName defines the name of the new task
  98533. * @param url defines the url of the file to load
  98534. * @param extensions defines the extension to use to load the cube map (can be null)
  98535. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98536. * @param files defines the list of files to load (can be null)
  98537. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98538. */
  98539. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98540. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98541. this._tasks.push(task);
  98542. return task;
  98543. };
  98544. /**
  98545. *
  98546. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98547. * @param taskName defines the name of the new task
  98548. * @param url defines the url of the file to load
  98549. * @param size defines the size you want for the cubemap (can be null)
  98550. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98551. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98552. * @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)
  98553. * @param reserved Internal use only
  98554. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98555. */
  98556. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98557. if (noMipmap === void 0) { noMipmap = false; }
  98558. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98559. if (gammaSpace === void 0) { gammaSpace = false; }
  98560. if (reserved === void 0) { reserved = false; }
  98561. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98562. this._tasks.push(task);
  98563. return task;
  98564. };
  98565. /**
  98566. * Remove a task from the assets manager.
  98567. * @param task the task to remove
  98568. */
  98569. AssetsManager.prototype.removeTask = function (task) {
  98570. var index = this._tasks.indexOf(task);
  98571. if (index > -1) {
  98572. this._tasks.splice(index, 1);
  98573. }
  98574. };
  98575. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98576. this._waitingTasksCount--;
  98577. try {
  98578. if (this.onProgress) {
  98579. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98580. }
  98581. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98582. }
  98583. catch (e) {
  98584. BABYLON.Tools.Error("Error running progress callbacks.");
  98585. console.log(e);
  98586. }
  98587. if (this._waitingTasksCount === 0) {
  98588. try {
  98589. if (this.onFinish) {
  98590. this.onFinish(this._tasks);
  98591. }
  98592. // Let's remove successfull tasks
  98593. var currentTasks = this._tasks.slice();
  98594. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98595. var task = currentTasks_1[_i];
  98596. if (task.taskState === AssetTaskState.DONE) {
  98597. var index = this._tasks.indexOf(task);
  98598. if (index > -1) {
  98599. this._tasks.splice(index, 1);
  98600. }
  98601. }
  98602. }
  98603. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98604. }
  98605. catch (e) {
  98606. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98607. console.log(e);
  98608. }
  98609. this._isLoading = false;
  98610. this._scene.getEngine().hideLoadingUI();
  98611. }
  98612. };
  98613. AssetsManager.prototype._runTask = function (task) {
  98614. var _this = this;
  98615. var done = function () {
  98616. try {
  98617. if (_this.onTaskSuccess) {
  98618. _this.onTaskSuccess(task);
  98619. }
  98620. _this.onTaskSuccessObservable.notifyObservers(task);
  98621. _this._decreaseWaitingTasksCount(task);
  98622. }
  98623. catch (e) {
  98624. error("Error executing task success callbacks", e);
  98625. }
  98626. };
  98627. var error = function (message, exception) {
  98628. task._setErrorObject(message, exception);
  98629. if (_this.onTaskError) {
  98630. _this.onTaskError(task);
  98631. }
  98632. _this.onTaskErrorObservable.notifyObservers(task);
  98633. _this._decreaseWaitingTasksCount(task);
  98634. };
  98635. task.run(this._scene, done, error);
  98636. };
  98637. /**
  98638. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98639. * @return the current instance of the {BABYLON.AssetsManager}
  98640. */
  98641. AssetsManager.prototype.reset = function () {
  98642. this._isLoading = false;
  98643. this._tasks = new Array();
  98644. return this;
  98645. };
  98646. /**
  98647. * Start the loading process
  98648. * @return the current instance of the {BABYLON.AssetsManager}
  98649. */
  98650. AssetsManager.prototype.load = function () {
  98651. if (this._isLoading) {
  98652. return this;
  98653. }
  98654. this._isLoading = true;
  98655. this._waitingTasksCount = this._tasks.length;
  98656. this._totalTasksCount = this._tasks.length;
  98657. if (this._waitingTasksCount === 0) {
  98658. this._isLoading = false;
  98659. if (this.onFinish) {
  98660. this.onFinish(this._tasks);
  98661. }
  98662. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98663. return this;
  98664. }
  98665. if (this.useDefaultLoadingScreen) {
  98666. this._scene.getEngine().displayLoadingUI();
  98667. }
  98668. for (var index = 0; index < this._tasks.length; index++) {
  98669. var task = this._tasks[index];
  98670. if (task.taskState === AssetTaskState.INIT) {
  98671. this._runTask(task);
  98672. }
  98673. }
  98674. return this;
  98675. };
  98676. return AssetsManager;
  98677. }());
  98678. BABYLON.AssetsManager = AssetsManager;
  98679. })(BABYLON || (BABYLON = {}));
  98680. //# sourceMappingURL=babylon.assetsManager.js.map
  98681. var BABYLON;
  98682. (function (BABYLON) {
  98683. var serializedGeometries = [];
  98684. var serializeGeometry = function (geometry, serializationGeometries) {
  98685. if (serializedGeometries[geometry.id]) {
  98686. return;
  98687. }
  98688. if (geometry.doNotSerialize) {
  98689. return;
  98690. }
  98691. if (geometry instanceof BABYLON.BoxGeometry) {
  98692. serializationGeometries.boxes.push(geometry.serialize());
  98693. }
  98694. else if (geometry instanceof BABYLON.SphereGeometry) {
  98695. serializationGeometries.spheres.push(geometry.serialize());
  98696. }
  98697. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98698. serializationGeometries.cylinders.push(geometry.serialize());
  98699. }
  98700. else if (geometry instanceof BABYLON.TorusGeometry) {
  98701. serializationGeometries.toruses.push(geometry.serialize());
  98702. }
  98703. else if (geometry instanceof BABYLON.GroundGeometry) {
  98704. serializationGeometries.grounds.push(geometry.serialize());
  98705. }
  98706. else if (geometry instanceof BABYLON.Plane) {
  98707. serializationGeometries.planes.push(geometry.serialize());
  98708. }
  98709. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98710. serializationGeometries.torusKnots.push(geometry.serialize());
  98711. }
  98712. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98713. throw new Error("Unknown primitive type");
  98714. }
  98715. else {
  98716. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98717. }
  98718. serializedGeometries[geometry.id] = true;
  98719. };
  98720. var serializeMesh = function (mesh, serializationScene) {
  98721. var serializationObject = {};
  98722. // Geometry
  98723. var geometry = mesh._geometry;
  98724. if (geometry) {
  98725. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98726. // 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
  98727. serializeGeometry(geometry, serializationScene.geometries);
  98728. }
  98729. }
  98730. // Custom
  98731. if (mesh.serialize) {
  98732. mesh.serialize(serializationObject);
  98733. }
  98734. return serializationObject;
  98735. };
  98736. var finalizeSingleMesh = function (mesh, serializationObject) {
  98737. //only works if the mesh is already loaded
  98738. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98739. //serialize material
  98740. if (mesh.material) {
  98741. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98742. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98743. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98744. serializationObject.multiMaterials.push(mesh.material.serialize());
  98745. }
  98746. }
  98747. else {
  98748. serializationObject.materials = serializationObject.materials || [];
  98749. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98750. serializationObject.materials.push(mesh.material.serialize());
  98751. }
  98752. }
  98753. }
  98754. //serialize geometry
  98755. var geometry = mesh._geometry;
  98756. if (geometry) {
  98757. if (!serializationObject.geometries) {
  98758. serializationObject.geometries = {};
  98759. serializationObject.geometries.boxes = [];
  98760. serializationObject.geometries.spheres = [];
  98761. serializationObject.geometries.cylinders = [];
  98762. serializationObject.geometries.toruses = [];
  98763. serializationObject.geometries.grounds = [];
  98764. serializationObject.geometries.planes = [];
  98765. serializationObject.geometries.torusKnots = [];
  98766. serializationObject.geometries.vertexData = [];
  98767. }
  98768. serializeGeometry(geometry, serializationObject.geometries);
  98769. }
  98770. // Skeletons
  98771. if (mesh.skeleton) {
  98772. serializationObject.skeletons = serializationObject.skeletons || [];
  98773. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98774. }
  98775. //serialize the actual mesh
  98776. serializationObject.meshes = serializationObject.meshes || [];
  98777. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98778. }
  98779. };
  98780. var SceneSerializer = /** @class */ (function () {
  98781. function SceneSerializer() {
  98782. }
  98783. SceneSerializer.ClearCache = function () {
  98784. serializedGeometries = [];
  98785. };
  98786. SceneSerializer.Serialize = function (scene) {
  98787. var serializationObject = {};
  98788. SceneSerializer.ClearCache();
  98789. // Scene
  98790. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98791. serializationObject.autoClear = scene.autoClear;
  98792. serializationObject.clearColor = scene.clearColor.asArray();
  98793. serializationObject.ambientColor = scene.ambientColor.asArray();
  98794. serializationObject.gravity = scene.gravity.asArray();
  98795. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98796. serializationObject.workerCollisions = scene.workerCollisions;
  98797. // Fog
  98798. if (scene.fogMode && scene.fogMode !== 0) {
  98799. serializationObject.fogMode = scene.fogMode;
  98800. serializationObject.fogColor = scene.fogColor.asArray();
  98801. serializationObject.fogStart = scene.fogStart;
  98802. serializationObject.fogEnd = scene.fogEnd;
  98803. serializationObject.fogDensity = scene.fogDensity;
  98804. }
  98805. //Physics
  98806. if (scene.isPhysicsEnabled()) {
  98807. var physicEngine = scene.getPhysicsEngine();
  98808. if (physicEngine) {
  98809. serializationObject.physicsEnabled = true;
  98810. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98811. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98812. }
  98813. }
  98814. // Metadata
  98815. if (scene.metadata) {
  98816. serializationObject.metadata = scene.metadata;
  98817. }
  98818. // Morph targets
  98819. serializationObject.morphTargetManagers = [];
  98820. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98821. var abstractMesh = _a[_i];
  98822. var manager = abstractMesh.morphTargetManager;
  98823. if (manager) {
  98824. serializationObject.morphTargetManagers.push(manager.serialize());
  98825. }
  98826. }
  98827. // Lights
  98828. serializationObject.lights = [];
  98829. var index;
  98830. var light;
  98831. for (index = 0; index < scene.lights.length; index++) {
  98832. light = scene.lights[index];
  98833. if (!light.doNotSerialize) {
  98834. serializationObject.lights.push(light.serialize());
  98835. }
  98836. }
  98837. // Cameras
  98838. serializationObject.cameras = [];
  98839. for (index = 0; index < scene.cameras.length; index++) {
  98840. var camera = scene.cameras[index];
  98841. if (!camera.doNotSerialize) {
  98842. serializationObject.cameras.push(camera.serialize());
  98843. }
  98844. }
  98845. if (scene.activeCamera) {
  98846. serializationObject.activeCameraID = scene.activeCamera.id;
  98847. }
  98848. // Animations
  98849. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98850. // Materials
  98851. serializationObject.materials = [];
  98852. serializationObject.multiMaterials = [];
  98853. var material;
  98854. for (index = 0; index < scene.materials.length; index++) {
  98855. material = scene.materials[index];
  98856. if (!material.doNotSerialize) {
  98857. serializationObject.materials.push(material.serialize());
  98858. }
  98859. }
  98860. // MultiMaterials
  98861. serializationObject.multiMaterials = [];
  98862. for (index = 0; index < scene.multiMaterials.length; index++) {
  98863. var multiMaterial = scene.multiMaterials[index];
  98864. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98865. }
  98866. // Environment texture
  98867. if (scene.environmentTexture) {
  98868. serializationObject.environmentTexture = scene.environmentTexture.name;
  98869. }
  98870. // Skeletons
  98871. serializationObject.skeletons = [];
  98872. for (index = 0; index < scene.skeletons.length; index++) {
  98873. var skeleton = scene.skeletons[index];
  98874. if (!skeleton.doNotSerialize) {
  98875. serializationObject.skeletons.push(skeleton.serialize());
  98876. }
  98877. }
  98878. // Transform nodes
  98879. serializationObject.transformNodes = [];
  98880. for (index = 0; index < scene.transformNodes.length; index++) {
  98881. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98882. }
  98883. // Geometries
  98884. serializationObject.geometries = {};
  98885. serializationObject.geometries.boxes = [];
  98886. serializationObject.geometries.spheres = [];
  98887. serializationObject.geometries.cylinders = [];
  98888. serializationObject.geometries.toruses = [];
  98889. serializationObject.geometries.grounds = [];
  98890. serializationObject.geometries.planes = [];
  98891. serializationObject.geometries.torusKnots = [];
  98892. serializationObject.geometries.vertexData = [];
  98893. serializedGeometries = [];
  98894. var geometries = scene.getGeometries();
  98895. for (index = 0; index < geometries.length; index++) {
  98896. var geometry = geometries[index];
  98897. if (geometry.isReady()) {
  98898. serializeGeometry(geometry, serializationObject.geometries);
  98899. }
  98900. }
  98901. // Meshes
  98902. serializationObject.meshes = [];
  98903. for (index = 0; index < scene.meshes.length; index++) {
  98904. var abstractMesh = scene.meshes[index];
  98905. if (abstractMesh instanceof BABYLON.Mesh) {
  98906. var mesh = abstractMesh;
  98907. if (!mesh.doNotSerialize) {
  98908. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98909. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98910. }
  98911. }
  98912. }
  98913. }
  98914. // Particles Systems
  98915. serializationObject.particleSystems = [];
  98916. for (index = 0; index < scene.particleSystems.length; index++) {
  98917. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98918. }
  98919. // Shadows
  98920. serializationObject.shadowGenerators = [];
  98921. for (index = 0; index < scene.lights.length; index++) {
  98922. light = scene.lights[index];
  98923. var shadowGenerator = light.getShadowGenerator();
  98924. if (shadowGenerator) {
  98925. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98926. }
  98927. }
  98928. // Action Manager
  98929. if (scene.actionManager) {
  98930. serializationObject.actions = scene.actionManager.serialize("scene");
  98931. }
  98932. // Audio
  98933. serializationObject.sounds = [];
  98934. for (index = 0; index < scene.soundTracks.length; index++) {
  98935. var soundtrack = scene.soundTracks[index];
  98936. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98937. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98938. }
  98939. }
  98940. // Components
  98941. for (var _b = 0, _c = scene._components; _b < _c.length; _b++) {
  98942. var component = _c[_b];
  98943. component.serialize(serializationObject);
  98944. }
  98945. return serializationObject;
  98946. };
  98947. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98948. if (withParents === void 0) { withParents = false; }
  98949. if (withChildren === void 0) { withChildren = false; }
  98950. var serializationObject = {};
  98951. SceneSerializer.ClearCache();
  98952. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98953. if (withParents || withChildren) {
  98954. //deliberate for loop! not for each, appended should be processed as well.
  98955. for (var i = 0; i < toSerialize.length; ++i) {
  98956. if (withChildren) {
  98957. toSerialize[i].getDescendants().forEach(function (node) {
  98958. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98959. toSerialize.push(node);
  98960. }
  98961. });
  98962. }
  98963. //make sure the array doesn't contain the object already
  98964. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98965. toSerialize.push(toSerialize[i].parent);
  98966. }
  98967. }
  98968. }
  98969. toSerialize.forEach(function (mesh) {
  98970. finalizeSingleMesh(mesh, serializationObject);
  98971. });
  98972. return serializationObject;
  98973. };
  98974. return SceneSerializer;
  98975. }());
  98976. BABYLON.SceneSerializer = SceneSerializer;
  98977. })(BABYLON || (BABYLON = {}));
  98978. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98979. var BABYLON;
  98980. (function (BABYLON) {
  98981. var ReflectionProbe = /** @class */ (function () {
  98982. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98984. var _this = this;
  98985. this.name = name;
  98986. this._viewMatrix = BABYLON.Matrix.Identity();
  98987. this._target = BABYLON.Vector3.Zero();
  98988. this._add = BABYLON.Vector3.Zero();
  98989. this._invertYAxis = false;
  98990. this.position = BABYLON.Vector3.Zero();
  98991. this._scene = scene;
  98992. this._scene.reflectionProbes.push(this);
  98993. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98994. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98995. switch (faceIndex) {
  98996. case 0:
  98997. _this._add.copyFromFloats(1, 0, 0);
  98998. break;
  98999. case 1:
  99000. _this._add.copyFromFloats(-1, 0, 0);
  99001. break;
  99002. case 2:
  99003. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99004. break;
  99005. case 3:
  99006. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99007. break;
  99008. case 4:
  99009. _this._add.copyFromFloats(0, 0, 1);
  99010. break;
  99011. case 5:
  99012. _this._add.copyFromFloats(0, 0, -1);
  99013. break;
  99014. }
  99015. if (_this._attachedMesh) {
  99016. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99017. }
  99018. _this.position.addToRef(_this._add, _this._target);
  99019. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99020. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99021. scene._forcedViewPosition = _this.position;
  99022. });
  99023. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99024. scene._forcedViewPosition = null;
  99025. scene.updateTransformMatrix(true);
  99026. });
  99027. if (scene.activeCamera) {
  99028. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99029. }
  99030. }
  99031. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99032. get: function () {
  99033. return this._renderTargetTexture.samples;
  99034. },
  99035. set: function (value) {
  99036. this._renderTargetTexture.samples = value;
  99037. },
  99038. enumerable: true,
  99039. configurable: true
  99040. });
  99041. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99042. get: function () {
  99043. return this._renderTargetTexture.refreshRate;
  99044. },
  99045. set: function (value) {
  99046. this._renderTargetTexture.refreshRate = value;
  99047. },
  99048. enumerable: true,
  99049. configurable: true
  99050. });
  99051. ReflectionProbe.prototype.getScene = function () {
  99052. return this._scene;
  99053. };
  99054. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99055. get: function () {
  99056. return this._renderTargetTexture;
  99057. },
  99058. enumerable: true,
  99059. configurable: true
  99060. });
  99061. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99062. get: function () {
  99063. return this._renderTargetTexture.renderList;
  99064. },
  99065. enumerable: true,
  99066. configurable: true
  99067. });
  99068. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99069. this._attachedMesh = mesh;
  99070. };
  99071. /**
  99072. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99073. *
  99074. * @param renderingGroupId The rendering group id corresponding to its index
  99075. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99076. */
  99077. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99078. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99079. };
  99080. ReflectionProbe.prototype.dispose = function () {
  99081. var index = this._scene.reflectionProbes.indexOf(this);
  99082. if (index !== -1) {
  99083. // Remove from the scene if found
  99084. this._scene.reflectionProbes.splice(index, 1);
  99085. }
  99086. if (this._renderTargetTexture) {
  99087. this._renderTargetTexture.dispose();
  99088. this._renderTargetTexture = null;
  99089. }
  99090. };
  99091. return ReflectionProbe;
  99092. }());
  99093. BABYLON.ReflectionProbe = ReflectionProbe;
  99094. })(BABYLON || (BABYLON = {}));
  99095. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99096. var BABYLON;
  99097. (function (BABYLON) {
  99098. /**
  99099. * Defines the layer scene component responsible to manage any layers
  99100. * in a given scene.
  99101. */
  99102. var LayerSceneComponent = /** @class */ (function () {
  99103. /**
  99104. * Creates a new instance of the component for the given scene
  99105. * @param scene Defines the scene to register the component in
  99106. */
  99107. function LayerSceneComponent(scene) {
  99108. /**
  99109. * The component name helpfull to identify the component in the list of scene components.
  99110. */
  99111. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99112. this.scene = scene;
  99113. this._engine = scene.getEngine();
  99114. this._layers = scene.layers = new Array();
  99115. }
  99116. /**
  99117. * Registers the component in a given scene
  99118. */
  99119. LayerSceneComponent.prototype.register = function () {
  99120. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99121. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99122. };
  99123. /**
  99124. * Rebuilds the elements related to this component in case of
  99125. * context lost for instance.
  99126. */
  99127. LayerSceneComponent.prototype.rebuild = function () {
  99128. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  99129. var layer = _a[_i];
  99130. layer._rebuild();
  99131. }
  99132. };
  99133. /**
  99134. * Serializes the component data to the specified json object
  99135. * @param serializationObject The object to serialize to
  99136. */
  99137. LayerSceneComponent.prototype.serialize = function (serializationObject) {
  99138. // TODO. Implement layer serialization
  99139. // serializationObject.layers = [];
  99140. // for (let layer of this._layers) {
  99141. // if (layer.serialize) {
  99142. // serializationObject.layers.push(layer.serialize());
  99143. // }
  99144. // }
  99145. };
  99146. /**
  99147. * Adds all the element from the container to the scene
  99148. * @param container the container holding the elements
  99149. */
  99150. LayerSceneComponent.prototype.addFromContainer = function (container) {
  99151. if (!container.layers) {
  99152. return;
  99153. }
  99154. // container.layers.forEach((o) => {
  99155. // this.scene.addLayer(o);
  99156. // });
  99157. };
  99158. /**
  99159. * Removes all the elements in the container from the scene
  99160. * @param container contains the elements to remove
  99161. */
  99162. LayerSceneComponent.prototype.removeFromContainer = function (container) {
  99163. if (!container.layers) {
  99164. return;
  99165. }
  99166. // container.layers.forEach((o) => {
  99167. // this.scene.removeLayer(o);
  99168. // });
  99169. };
  99170. /**
  99171. * Disposes the component and the associated ressources.
  99172. */
  99173. LayerSceneComponent.prototype.dispose = function () {
  99174. while (this._layers.length) {
  99175. this._layers[0].dispose();
  99176. }
  99177. };
  99178. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99179. if (this._layers.length) {
  99180. this._engine.setDepthBuffer(false);
  99181. var cameraLayerMask = camera.layerMask;
  99182. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  99183. var layer = _a[_i];
  99184. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99185. layer.render();
  99186. }
  99187. }
  99188. this._engine.setDepthBuffer(true);
  99189. }
  99190. };
  99191. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99192. this._draw(camera, true);
  99193. };
  99194. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99195. this._draw(camera, false);
  99196. };
  99197. return LayerSceneComponent;
  99198. }());
  99199. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99200. })(BABYLON || (BABYLON = {}));
  99201. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99202. var BABYLON;
  99203. (function (BABYLON) {
  99204. var Layer = /** @class */ (function () {
  99205. function Layer(name, imgUrl, scene, isBackground, color) {
  99206. this.name = name;
  99207. this.scale = new BABYLON.Vector2(1, 1);
  99208. this.offset = new BABYLON.Vector2(0, 0);
  99209. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99210. this.layerMask = 0x0FFFFFFF;
  99211. this._vertexBuffers = {};
  99212. // Events
  99213. /**
  99214. * An event triggered when the layer is disposed.
  99215. */
  99216. this.onDisposeObservable = new BABYLON.Observable();
  99217. /**
  99218. * An event triggered before rendering the scene
  99219. */
  99220. this.onBeforeRenderObservable = new BABYLON.Observable();
  99221. /**
  99222. * An event triggered after rendering the scene
  99223. */
  99224. this.onAfterRenderObservable = new BABYLON.Observable();
  99225. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99226. this.isBackground = isBackground === undefined ? true : isBackground;
  99227. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99228. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99229. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99230. if (!layerComponent) {
  99231. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99232. this._scene._addComponent(layerComponent);
  99233. }
  99234. this._scene.layers.push(this);
  99235. var engine = this._scene.getEngine();
  99236. // VBO
  99237. var vertices = [];
  99238. vertices.push(1, 1);
  99239. vertices.push(-1, 1);
  99240. vertices.push(-1, -1);
  99241. vertices.push(1, -1);
  99242. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99244. this._createIndexBuffer();
  99245. // Effects
  99246. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99247. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99248. }
  99249. Object.defineProperty(Layer.prototype, "onDispose", {
  99250. set: function (callback) {
  99251. if (this._onDisposeObserver) {
  99252. this.onDisposeObservable.remove(this._onDisposeObserver);
  99253. }
  99254. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99255. },
  99256. enumerable: true,
  99257. configurable: true
  99258. });
  99259. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99260. set: function (callback) {
  99261. if (this._onBeforeRenderObserver) {
  99262. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99263. }
  99264. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99265. },
  99266. enumerable: true,
  99267. configurable: true
  99268. });
  99269. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99270. set: function (callback) {
  99271. if (this._onAfterRenderObserver) {
  99272. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99273. }
  99274. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99275. },
  99276. enumerable: true,
  99277. configurable: true
  99278. });
  99279. Layer.prototype._createIndexBuffer = function () {
  99280. var engine = this._scene.getEngine();
  99281. // Indices
  99282. var indices = [];
  99283. indices.push(0);
  99284. indices.push(1);
  99285. indices.push(2);
  99286. indices.push(0);
  99287. indices.push(2);
  99288. indices.push(3);
  99289. this._indexBuffer = engine.createIndexBuffer(indices);
  99290. };
  99291. Layer.prototype._rebuild = function () {
  99292. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99293. if (vb) {
  99294. vb._rebuild();
  99295. }
  99296. this._createIndexBuffer();
  99297. };
  99298. Layer.prototype.render = function () {
  99299. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99300. // Check
  99301. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99302. return;
  99303. var engine = this._scene.getEngine();
  99304. this.onBeforeRenderObservable.notifyObservers(this);
  99305. // Render
  99306. engine.enableEffect(currentEffect);
  99307. engine.setState(false);
  99308. // Texture
  99309. currentEffect.setTexture("textureSampler", this.texture);
  99310. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99311. // Color
  99312. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99313. // Scale / offset
  99314. currentEffect.setVector2("offset", this.offset);
  99315. currentEffect.setVector2("scale", this.scale);
  99316. // VBOs
  99317. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99318. // Draw order
  99319. if (!this.alphaTest) {
  99320. engine.setAlphaMode(this.alphaBlendingMode);
  99321. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99323. }
  99324. else {
  99325. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99326. }
  99327. this.onAfterRenderObservable.notifyObservers(this);
  99328. };
  99329. Layer.prototype.dispose = function () {
  99330. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99331. if (vertexBuffer) {
  99332. vertexBuffer.dispose();
  99333. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99334. }
  99335. if (this._indexBuffer) {
  99336. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99337. this._indexBuffer = null;
  99338. }
  99339. if (this.texture) {
  99340. this.texture.dispose();
  99341. this.texture = null;
  99342. }
  99343. // Remove from scene
  99344. var index = this._scene.layers.indexOf(this);
  99345. this._scene.layers.splice(index, 1);
  99346. // Callback
  99347. this.onDisposeObservable.notifyObservers(this);
  99348. this.onDisposeObservable.clear();
  99349. this.onAfterRenderObservable.clear();
  99350. this.onBeforeRenderObservable.clear();
  99351. };
  99352. return Layer;
  99353. }());
  99354. BABYLON.Layer = Layer;
  99355. })(BABYLON || (BABYLON = {}));
  99356. //# sourceMappingURL=babylon.layer.js.map
  99357. var BABYLON;
  99358. (function (BABYLON) {
  99359. var TextureTools = /** @class */ (function () {
  99360. function TextureTools() {
  99361. }
  99362. /**
  99363. * Uses the GPU to create a copy texture rescaled at a given size
  99364. * @param texture Texture to copy from
  99365. * @param width Desired width
  99366. * @param height Desired height
  99367. * @return Generated texture
  99368. */
  99369. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99370. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99371. var scene = texture.getScene();
  99372. var engine = scene.getEngine();
  99373. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99374. rtt.wrapU = texture.wrapU;
  99375. rtt.wrapV = texture.wrapV;
  99376. rtt.uOffset = texture.uOffset;
  99377. rtt.vOffset = texture.vOffset;
  99378. rtt.uScale = texture.uScale;
  99379. rtt.vScale = texture.vScale;
  99380. rtt.uAng = texture.uAng;
  99381. rtt.vAng = texture.vAng;
  99382. rtt.wAng = texture.wAng;
  99383. rtt.coordinatesIndex = texture.coordinatesIndex;
  99384. rtt.level = texture.level;
  99385. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99386. rtt._texture.isReady = false;
  99387. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99388. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99389. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99390. passPostProcess.getEffect().executeWhenCompiled(function () {
  99391. passPostProcess.onApply = function (effect) {
  99392. effect.setTexture("textureSampler", texture);
  99393. };
  99394. var internalTexture = rtt.getInternalTexture();
  99395. if (internalTexture) {
  99396. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99397. engine.unBindFramebuffer(internalTexture);
  99398. rtt.disposeFramebufferObjects();
  99399. passPostProcess.dispose();
  99400. internalTexture.isReady = true;
  99401. }
  99402. });
  99403. return rtt;
  99404. };
  99405. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99406. if (!scene._environmentBRDFTexture) {
  99407. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99408. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99409. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99410. scene._environmentBRDFTexture = texture;
  99411. }
  99412. return scene._environmentBRDFTexture;
  99413. };
  99414. 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=";
  99415. return TextureTools;
  99416. }());
  99417. BABYLON.TextureTools = TextureTools;
  99418. })(BABYLON || (BABYLON = {}));
  99419. //# sourceMappingURL=babylon.textureTools.js.map
  99420. var BABYLON;
  99421. (function (BABYLON) {
  99422. var FramingBehavior = /** @class */ (function () {
  99423. function FramingBehavior() {
  99424. this._mode = FramingBehavior.FitFrustumSidesMode;
  99425. this._radiusScale = 1.0;
  99426. this._positionScale = 0.5;
  99427. this._defaultElevation = 0.3;
  99428. this._elevationReturnTime = 1500;
  99429. this._elevationReturnWaitTime = 1000;
  99430. this._zoomStopsAnimation = false;
  99431. this._framingTime = 1500;
  99432. this._isPointerDown = false;
  99433. this._lastInteractionTime = -Infinity;
  99434. // Framing control
  99435. this._animatables = new Array();
  99436. this._betaIsAnimating = false;
  99437. }
  99438. Object.defineProperty(FramingBehavior.prototype, "name", {
  99439. get: function () {
  99440. return "Framing";
  99441. },
  99442. enumerable: true,
  99443. configurable: true
  99444. });
  99445. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99446. /**
  99447. * Gets current mode used by the behavior.
  99448. */
  99449. get: function () {
  99450. return this._mode;
  99451. },
  99452. /**
  99453. * Sets the current mode used by the behavior
  99454. */
  99455. set: function (mode) {
  99456. this._mode = mode;
  99457. },
  99458. enumerable: true,
  99459. configurable: true
  99460. });
  99461. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99462. /**
  99463. * Gets the scale applied to the radius
  99464. */
  99465. get: function () {
  99466. return this._radiusScale;
  99467. },
  99468. /**
  99469. * Sets the scale applied to the radius (1 by default)
  99470. */
  99471. set: function (radius) {
  99472. this._radiusScale = radius;
  99473. },
  99474. enumerable: true,
  99475. configurable: true
  99476. });
  99477. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99478. /**
  99479. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99480. */
  99481. get: function () {
  99482. return this._positionScale;
  99483. },
  99484. /**
  99485. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99486. */
  99487. set: function (scale) {
  99488. this._positionScale = scale;
  99489. },
  99490. enumerable: true,
  99491. configurable: true
  99492. });
  99493. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99494. /**
  99495. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99496. * behaviour is triggered, in radians.
  99497. */
  99498. get: function () {
  99499. return this._defaultElevation;
  99500. },
  99501. /**
  99502. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99503. * behaviour is triggered, in radians.
  99504. */
  99505. set: function (elevation) {
  99506. this._defaultElevation = elevation;
  99507. },
  99508. enumerable: true,
  99509. configurable: true
  99510. });
  99511. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99512. /**
  99513. * Gets the time (in milliseconds) taken to return to the default beta position.
  99514. * Negative value indicates camera should not return to default.
  99515. */
  99516. get: function () {
  99517. return this._elevationReturnTime;
  99518. },
  99519. /**
  99520. * Sets the time (in milliseconds) taken to return to the default beta position.
  99521. * Negative value indicates camera should not return to default.
  99522. */
  99523. set: function (speed) {
  99524. this._elevationReturnTime = speed;
  99525. },
  99526. enumerable: true,
  99527. configurable: true
  99528. });
  99529. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99530. /**
  99531. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99532. */
  99533. get: function () {
  99534. return this._elevationReturnWaitTime;
  99535. },
  99536. /**
  99537. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99538. */
  99539. set: function (time) {
  99540. this._elevationReturnWaitTime = time;
  99541. },
  99542. enumerable: true,
  99543. configurable: true
  99544. });
  99545. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99546. /**
  99547. * Gets the flag that indicates if user zooming should stop animation.
  99548. */
  99549. get: function () {
  99550. return this._zoomStopsAnimation;
  99551. },
  99552. /**
  99553. * Sets the flag that indicates if user zooming should stop animation.
  99554. */
  99555. set: function (flag) {
  99556. this._zoomStopsAnimation = flag;
  99557. },
  99558. enumerable: true,
  99559. configurable: true
  99560. });
  99561. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99562. /**
  99563. * Gets the transition time when framing the mesh, in milliseconds
  99564. */
  99565. get: function () {
  99566. return this._framingTime;
  99567. },
  99568. /**
  99569. * Sets the transition time when framing the mesh, in milliseconds
  99570. */
  99571. set: function (time) {
  99572. this._framingTime = time;
  99573. },
  99574. enumerable: true,
  99575. configurable: true
  99576. });
  99577. FramingBehavior.prototype.init = function () {
  99578. // Do notihng
  99579. };
  99580. FramingBehavior.prototype.attach = function (camera) {
  99581. var _this = this;
  99582. this._attachedCamera = camera;
  99583. var scene = this._attachedCamera.getScene();
  99584. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99585. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99586. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99587. _this._isPointerDown = true;
  99588. return;
  99589. }
  99590. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99591. _this._isPointerDown = false;
  99592. }
  99593. });
  99594. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99595. if (mesh) {
  99596. _this.zoomOnMesh(mesh);
  99597. }
  99598. });
  99599. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99600. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99601. _this._applyUserInteraction();
  99602. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99603. // back to the default position after a given timeout
  99604. _this._maintainCameraAboveGround();
  99605. });
  99606. };
  99607. FramingBehavior.prototype.detach = function () {
  99608. if (!this._attachedCamera) {
  99609. return;
  99610. }
  99611. var scene = this._attachedCamera.getScene();
  99612. if (this._onPrePointerObservableObserver) {
  99613. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99614. }
  99615. if (this._onAfterCheckInputsObserver) {
  99616. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99617. }
  99618. if (this._onMeshTargetChangedObserver) {
  99619. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99620. }
  99621. this._attachedCamera = null;
  99622. };
  99623. /**
  99624. * Targets the given mesh and updates zoom level accordingly.
  99625. * @param mesh The mesh to target.
  99626. * @param radius Optional. If a cached radius position already exists, overrides default.
  99627. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99628. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99629. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99630. */
  99631. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99632. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99633. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99634. mesh.computeWorldMatrix(true);
  99635. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99636. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99637. };
  99638. /**
  99639. * Targets the given mesh with its children and updates zoom level accordingly.
  99640. * @param mesh The mesh to target.
  99641. * @param radius Optional. If a cached radius position already exists, overrides default.
  99642. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99643. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99644. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99645. */
  99646. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99647. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99648. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99649. mesh.computeWorldMatrix(true);
  99650. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99651. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99652. };
  99653. /**
  99654. * Targets the given meshes with their children and updates zoom level accordingly.
  99655. * @param meshes The mesh to target.
  99656. * @param radius Optional. If a cached radius position already exists, overrides default.
  99657. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99658. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99659. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99660. */
  99661. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99662. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99663. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99664. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99665. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99666. for (var i = 0; i < meshes.length; i++) {
  99667. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99668. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99669. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99670. }
  99671. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99672. };
  99673. /**
  99674. * Targets the given mesh and updates zoom level accordingly.
  99675. * @param mesh The mesh to target.
  99676. * @param radius Optional. If a cached radius position already exists, overrides default.
  99677. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99678. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99679. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99680. */
  99681. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99682. var _this = this;
  99683. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99684. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99685. var zoomTarget;
  99686. if (!this._attachedCamera) {
  99687. return;
  99688. }
  99689. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99690. var bottom = minimumWorld.y;
  99691. var top = maximumWorld.y;
  99692. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99693. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99694. if (focusOnOriginXZ) {
  99695. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99696. }
  99697. else {
  99698. var centerWorld = minimumWorld.add(radiusWorld);
  99699. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99700. }
  99701. if (!this._vectorTransition) {
  99702. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99703. }
  99704. this._betaIsAnimating = true;
  99705. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99706. if (animatable) {
  99707. this._animatables.push(animatable);
  99708. }
  99709. // sets the radius and lower radius bounds
  99710. // Small delta ensures camera is not always at lower zoom limit.
  99711. var radius = 0;
  99712. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99713. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99714. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99715. radius = position;
  99716. }
  99717. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99718. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99719. if (this._attachedCamera.lowerRadiusLimit === null) {
  99720. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99721. }
  99722. }
  99723. // Set sensibilities
  99724. var extend = maximumWorld.subtract(minimumWorld).length();
  99725. this._attachedCamera.panningSensibility = 5000 / extend;
  99726. this._attachedCamera.wheelPrecision = 100 / radius;
  99727. // transition to new radius
  99728. if (!this._radiusTransition) {
  99729. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99730. }
  99731. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99732. _this.stopAllAnimations();
  99733. if (onAnimationEnd) {
  99734. onAnimationEnd();
  99735. }
  99736. if (_this._attachedCamera) {
  99737. _this._attachedCamera.storeState();
  99738. }
  99739. });
  99740. if (animatable) {
  99741. this._animatables.push(animatable);
  99742. }
  99743. };
  99744. /**
  99745. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99746. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99747. * frustum width.
  99748. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99749. * to fully enclose the mesh in the viewing frustum.
  99750. */
  99751. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99752. var size = maximumWorld.subtract(minimumWorld);
  99753. var boxVectorGlobalDiagonal = size.length();
  99754. var frustumSlope = this._getFrustumSlope();
  99755. // Formula for setting distance
  99756. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99757. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99758. // Horizon distance
  99759. var radius = radiusWithoutFraming * this._radiusScale;
  99760. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99761. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99762. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99763. var camera = this._attachedCamera;
  99764. if (!camera) {
  99765. return 0;
  99766. }
  99767. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99768. // Don't exceed the requested limit
  99769. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99770. }
  99771. // Don't exceed the upper radius limit
  99772. if (camera.upperRadiusLimit) {
  99773. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99774. }
  99775. return distance;
  99776. };
  99777. /**
  99778. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99779. * is automatically returned to its default position (expected to be above ground plane).
  99780. */
  99781. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99782. var _this = this;
  99783. if (this._elevationReturnTime < 0) {
  99784. return;
  99785. }
  99786. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99787. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99788. var limitBeta = Math.PI * 0.5;
  99789. // Bring the camera back up if below the ground plane
  99790. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99791. this._betaIsAnimating = true;
  99792. //Transition to new position
  99793. this.stopAllAnimations();
  99794. if (!this._betaTransition) {
  99795. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99796. }
  99797. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99798. _this._clearAnimationLocks();
  99799. _this.stopAllAnimations();
  99800. });
  99801. if (animatabe) {
  99802. this._animatables.push(animatabe);
  99803. }
  99804. }
  99805. };
  99806. /**
  99807. * Returns the frustum slope based on the canvas ratio and camera FOV
  99808. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99809. */
  99810. FramingBehavior.prototype._getFrustumSlope = function () {
  99811. // Calculate the viewport ratio
  99812. // Aspect Ratio is Height/Width.
  99813. var camera = this._attachedCamera;
  99814. if (!camera) {
  99815. return BABYLON.Vector2.Zero();
  99816. }
  99817. var engine = camera.getScene().getEngine();
  99818. var aspectRatio = engine.getAspectRatio(camera);
  99819. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99820. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99821. var frustumSlopeY = Math.tan(camera.fov / 2);
  99822. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99823. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99824. // along the forward vector.
  99825. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99826. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99827. };
  99828. /**
  99829. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99830. */
  99831. FramingBehavior.prototype._clearAnimationLocks = function () {
  99832. this._betaIsAnimating = false;
  99833. };
  99834. /**
  99835. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99836. */
  99837. FramingBehavior.prototype._applyUserInteraction = function () {
  99838. if (this.isUserIsMoving) {
  99839. this._lastInteractionTime = BABYLON.Tools.Now;
  99840. this.stopAllAnimations();
  99841. this._clearAnimationLocks();
  99842. }
  99843. };
  99844. /**
  99845. * Stops and removes all animations that have been applied to the camera
  99846. */
  99847. FramingBehavior.prototype.stopAllAnimations = function () {
  99848. if (this._attachedCamera) {
  99849. this._attachedCamera.animations = [];
  99850. }
  99851. while (this._animatables.length) {
  99852. if (this._animatables[0]) {
  99853. this._animatables[0].onAnimationEnd = null;
  99854. this._animatables[0].stop();
  99855. }
  99856. this._animatables.shift();
  99857. }
  99858. };
  99859. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99860. /**
  99861. * Gets a value indicating if the user is moving the camera
  99862. */
  99863. get: function () {
  99864. if (!this._attachedCamera) {
  99865. return false;
  99866. }
  99867. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99868. this._attachedCamera.inertialBetaOffset !== 0 ||
  99869. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99870. this._attachedCamera.inertialPanningX !== 0 ||
  99871. this._attachedCamera.inertialPanningY !== 0 ||
  99872. this._isPointerDown;
  99873. },
  99874. enumerable: true,
  99875. configurable: true
  99876. });
  99877. /**
  99878. * The easing function used by animations
  99879. */
  99880. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99881. /**
  99882. * The easing mode used by animations
  99883. */
  99884. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99885. // Statics
  99886. /**
  99887. * The camera can move all the way towards the mesh.
  99888. */
  99889. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99890. /**
  99891. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99892. */
  99893. FramingBehavior.FitFrustumSidesMode = 1;
  99894. return FramingBehavior;
  99895. }());
  99896. BABYLON.FramingBehavior = FramingBehavior;
  99897. })(BABYLON || (BABYLON = {}));
  99898. //# sourceMappingURL=babylon.framingBehavior.js.map
  99899. var BABYLON;
  99900. (function (BABYLON) {
  99901. /**
  99902. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99903. */
  99904. var BouncingBehavior = /** @class */ (function () {
  99905. function BouncingBehavior() {
  99906. /**
  99907. * The duration of the animation, in milliseconds
  99908. */
  99909. this.transitionDuration = 450;
  99910. /**
  99911. * Length of the distance animated by the transition when lower radius is reached
  99912. */
  99913. this.lowerRadiusTransitionRange = 2;
  99914. /**
  99915. * Length of the distance animated by the transition when upper radius is reached
  99916. */
  99917. this.upperRadiusTransitionRange = -2;
  99918. this._autoTransitionRange = false;
  99919. // Animations
  99920. this._radiusIsAnimating = false;
  99921. this._radiusBounceTransition = null;
  99922. this._animatables = new Array();
  99923. }
  99924. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99925. get: function () {
  99926. return "Bouncing";
  99927. },
  99928. enumerable: true,
  99929. configurable: true
  99930. });
  99931. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99932. /**
  99933. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99934. */
  99935. get: function () {
  99936. return this._autoTransitionRange;
  99937. },
  99938. /**
  99939. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99940. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99941. */
  99942. set: function (value) {
  99943. var _this = this;
  99944. if (this._autoTransitionRange === value) {
  99945. return;
  99946. }
  99947. this._autoTransitionRange = value;
  99948. var camera = this._attachedCamera;
  99949. if (!camera) {
  99950. return;
  99951. }
  99952. if (value) {
  99953. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99954. if (!mesh) {
  99955. return;
  99956. }
  99957. mesh.computeWorldMatrix(true);
  99958. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99959. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99960. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99961. });
  99962. }
  99963. else if (this._onMeshTargetChangedObserver) {
  99964. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99965. }
  99966. },
  99967. enumerable: true,
  99968. configurable: true
  99969. });
  99970. BouncingBehavior.prototype.init = function () {
  99971. // Do notihng
  99972. };
  99973. BouncingBehavior.prototype.attach = function (camera) {
  99974. var _this = this;
  99975. this._attachedCamera = camera;
  99976. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99977. if (!_this._attachedCamera) {
  99978. return;
  99979. }
  99980. // Add the bounce animation to the lower radius limit
  99981. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99982. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99983. }
  99984. // Add the bounce animation to the upper radius limit
  99985. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99986. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99987. }
  99988. });
  99989. };
  99990. BouncingBehavior.prototype.detach = function () {
  99991. if (!this._attachedCamera) {
  99992. return;
  99993. }
  99994. if (this._onAfterCheckInputsObserver) {
  99995. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99996. }
  99997. if (this._onMeshTargetChangedObserver) {
  99998. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99999. }
  100000. this._attachedCamera = null;
  100001. };
  100002. /**
  100003. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100004. * @param radiusLimit The limit to check against.
  100005. * @return Bool to indicate if at limit.
  100006. */
  100007. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100008. if (!this._attachedCamera) {
  100009. return false;
  100010. }
  100011. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100012. return true;
  100013. }
  100014. return false;
  100015. };
  100016. /**
  100017. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100018. * @param radiusDelta The delta by which to animate to. Can be negative.
  100019. */
  100020. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100021. var _this = this;
  100022. if (!this._attachedCamera) {
  100023. return;
  100024. }
  100025. if (!this._radiusBounceTransition) {
  100026. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100027. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100028. }
  100029. // Prevent zoom until bounce has completed
  100030. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100031. this._attachedCamera.wheelPrecision = Infinity;
  100032. this._attachedCamera.inertialRadiusOffset = 0;
  100033. // Animate to the radius limit
  100034. this.stopAllAnimations();
  100035. this._radiusIsAnimating = true;
  100036. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100037. if (animatable) {
  100038. this._animatables.push(animatable);
  100039. }
  100040. };
  100041. /**
  100042. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100043. */
  100044. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100045. this._radiusIsAnimating = false;
  100046. if (this._attachedCamera) {
  100047. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100048. }
  100049. };
  100050. /**
  100051. * Stops and removes all animations that have been applied to the camera
  100052. */
  100053. BouncingBehavior.prototype.stopAllAnimations = function () {
  100054. if (this._attachedCamera) {
  100055. this._attachedCamera.animations = [];
  100056. }
  100057. while (this._animatables.length) {
  100058. this._animatables[0].onAnimationEnd = null;
  100059. this._animatables[0].stop();
  100060. this._animatables.shift();
  100061. }
  100062. };
  100063. /**
  100064. * The easing function used by animations
  100065. */
  100066. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100067. /**
  100068. * The easing mode used by animations
  100069. */
  100070. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100071. return BouncingBehavior;
  100072. }());
  100073. BABYLON.BouncingBehavior = BouncingBehavior;
  100074. })(BABYLON || (BABYLON = {}));
  100075. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100076. var BABYLON;
  100077. (function (BABYLON) {
  100078. var AutoRotationBehavior = /** @class */ (function () {
  100079. function AutoRotationBehavior() {
  100080. this._zoomStopsAnimation = false;
  100081. this._idleRotationSpeed = 0.05;
  100082. this._idleRotationWaitTime = 2000;
  100083. this._idleRotationSpinupTime = 2000;
  100084. this._isPointerDown = false;
  100085. this._lastFrameTime = null;
  100086. this._lastInteractionTime = -Infinity;
  100087. this._cameraRotationSpeed = 0;
  100088. this._lastFrameRadius = 0;
  100089. }
  100090. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100091. get: function () {
  100092. return "AutoRotation";
  100093. },
  100094. enumerable: true,
  100095. configurable: true
  100096. });
  100097. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100098. /**
  100099. * Gets the flag that indicates if user zooming should stop animation.
  100100. */
  100101. get: function () {
  100102. return this._zoomStopsAnimation;
  100103. },
  100104. /**
  100105. * Sets the flag that indicates if user zooming should stop animation.
  100106. */
  100107. set: function (flag) {
  100108. this._zoomStopsAnimation = flag;
  100109. },
  100110. enumerable: true,
  100111. configurable: true
  100112. });
  100113. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100114. /**
  100115. * Gets the default speed at which the camera rotates around the model.
  100116. */
  100117. get: function () {
  100118. return this._idleRotationSpeed;
  100119. },
  100120. /**
  100121. * Sets the default speed at which the camera rotates around the model.
  100122. */
  100123. set: function (speed) {
  100124. this._idleRotationSpeed = speed;
  100125. },
  100126. enumerable: true,
  100127. configurable: true
  100128. });
  100129. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100130. /**
  100131. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100132. */
  100133. get: function () {
  100134. return this._idleRotationWaitTime;
  100135. },
  100136. /**
  100137. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100138. */
  100139. set: function (time) {
  100140. this._idleRotationWaitTime = time;
  100141. },
  100142. enumerable: true,
  100143. configurable: true
  100144. });
  100145. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100146. /**
  100147. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100148. */
  100149. get: function () {
  100150. return this._idleRotationSpinupTime;
  100151. },
  100152. /**
  100153. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100154. */
  100155. set: function (time) {
  100156. this._idleRotationSpinupTime = time;
  100157. },
  100158. enumerable: true,
  100159. configurable: true
  100160. });
  100161. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100162. /**
  100163. * Gets a value indicating if the camera is currently rotating because of this behavior
  100164. */
  100165. get: function () {
  100166. return Math.abs(this._cameraRotationSpeed) > 0;
  100167. },
  100168. enumerable: true,
  100169. configurable: true
  100170. });
  100171. AutoRotationBehavior.prototype.init = function () {
  100172. // Do notihng
  100173. };
  100174. AutoRotationBehavior.prototype.attach = function (camera) {
  100175. var _this = this;
  100176. this._attachedCamera = camera;
  100177. var scene = this._attachedCamera.getScene();
  100178. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100179. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100180. _this._isPointerDown = true;
  100181. return;
  100182. }
  100183. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100184. _this._isPointerDown = false;
  100185. }
  100186. });
  100187. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100188. var now = BABYLON.Tools.Now;
  100189. var dt = 0;
  100190. if (_this._lastFrameTime != null) {
  100191. dt = now - _this._lastFrameTime;
  100192. }
  100193. _this._lastFrameTime = now;
  100194. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100195. _this._applyUserInteraction();
  100196. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100197. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100198. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100199. // Step camera rotation by rotation speed
  100200. if (_this._attachedCamera) {
  100201. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100202. }
  100203. });
  100204. };
  100205. AutoRotationBehavior.prototype.detach = function () {
  100206. if (!this._attachedCamera) {
  100207. return;
  100208. }
  100209. var scene = this._attachedCamera.getScene();
  100210. if (this._onPrePointerObservableObserver) {
  100211. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100212. }
  100213. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100214. this._attachedCamera = null;
  100215. };
  100216. /**
  100217. * Returns true if user is scrolling.
  100218. * @return true if user is scrolling.
  100219. */
  100220. AutoRotationBehavior.prototype._userIsZooming = function () {
  100221. if (!this._attachedCamera) {
  100222. return false;
  100223. }
  100224. return this._attachedCamera.inertialRadiusOffset !== 0;
  100225. };
  100226. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100227. if (!this._attachedCamera) {
  100228. return false;
  100229. }
  100230. var zoomHasHitLimit = false;
  100231. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100232. zoomHasHitLimit = true;
  100233. }
  100234. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100235. this._lastFrameRadius = this._attachedCamera.radius;
  100236. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100237. };
  100238. /**
  100239. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100240. */
  100241. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100242. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100243. this._lastInteractionTime = BABYLON.Tools.Now;
  100244. }
  100245. };
  100246. // Tools
  100247. AutoRotationBehavior.prototype._userIsMoving = function () {
  100248. if (!this._attachedCamera) {
  100249. return false;
  100250. }
  100251. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100252. this._attachedCamera.inertialBetaOffset !== 0 ||
  100253. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100254. this._attachedCamera.inertialPanningX !== 0 ||
  100255. this._attachedCamera.inertialPanningY !== 0 ||
  100256. this._isPointerDown;
  100257. };
  100258. return AutoRotationBehavior;
  100259. }());
  100260. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100261. })(BABYLON || (BABYLON = {}));
  100262. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100263. var BABYLON;
  100264. (function (BABYLON) {
  100265. var NullEngineOptions = /** @class */ (function () {
  100266. function NullEngineOptions() {
  100267. this.renderWidth = 512;
  100268. this.renderHeight = 256;
  100269. this.textureSize = 512;
  100270. this.deterministicLockstep = false;
  100271. this.lockstepMaxSteps = 4;
  100272. }
  100273. return NullEngineOptions;
  100274. }());
  100275. BABYLON.NullEngineOptions = NullEngineOptions;
  100276. /**
  100277. * The null engine class provides support for headless version of babylon.js.
  100278. * This can be used in server side scenario or for testing purposes
  100279. */
  100280. var NullEngine = /** @class */ (function (_super) {
  100281. __extends(NullEngine, _super);
  100282. function NullEngine(options) {
  100283. if (options === void 0) { options = new NullEngineOptions(); }
  100284. var _this = _super.call(this, null) || this;
  100285. if (options.deterministicLockstep === undefined) {
  100286. options.deterministicLockstep = false;
  100287. }
  100288. if (options.lockstepMaxSteps === undefined) {
  100289. options.lockstepMaxSteps = 4;
  100290. }
  100291. _this._options = options;
  100292. // Init caps
  100293. // We consider we are on a webgl1 capable device
  100294. _this._caps = new BABYLON.EngineCapabilities();
  100295. _this._caps.maxTexturesImageUnits = 16;
  100296. _this._caps.maxVertexTextureImageUnits = 16;
  100297. _this._caps.maxTextureSize = 512;
  100298. _this._caps.maxCubemapTextureSize = 512;
  100299. _this._caps.maxRenderTextureSize = 512;
  100300. _this._caps.maxVertexAttribs = 16;
  100301. _this._caps.maxVaryingVectors = 16;
  100302. _this._caps.maxFragmentUniformVectors = 16;
  100303. _this._caps.maxVertexUniformVectors = 16;
  100304. // Extensions
  100305. _this._caps.standardDerivatives = false;
  100306. _this._caps.astc = null;
  100307. _this._caps.s3tc = null;
  100308. _this._caps.pvrtc = null;
  100309. _this._caps.etc1 = null;
  100310. _this._caps.etc2 = null;
  100311. _this._caps.textureAnisotropicFilterExtension = null;
  100312. _this._caps.maxAnisotropy = 0;
  100313. _this._caps.uintIndices = false;
  100314. _this._caps.fragmentDepthSupported = false;
  100315. _this._caps.highPrecisionShaderSupported = true;
  100316. _this._caps.colorBufferFloat = false;
  100317. _this._caps.textureFloat = false;
  100318. _this._caps.textureFloatLinearFiltering = false;
  100319. _this._caps.textureFloatRender = false;
  100320. _this._caps.textureHalfFloat = false;
  100321. _this._caps.textureHalfFloatLinearFiltering = false;
  100322. _this._caps.textureHalfFloatRender = false;
  100323. _this._caps.textureLOD = false;
  100324. _this._caps.drawBuffersExtension = false;
  100325. _this._caps.depthTextureExtension = false;
  100326. _this._caps.vertexArrayObject = false;
  100327. _this._caps.instancedArrays = false;
  100328. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100329. // Wrappers
  100330. if (typeof URL === "undefined") {
  100331. URL = {
  100332. createObjectURL: function () { },
  100333. revokeObjectURL: function () { }
  100334. };
  100335. }
  100336. if (typeof Blob === "undefined") {
  100337. Blob = function () { };
  100338. }
  100339. return _this;
  100340. }
  100341. NullEngine.prototype.isDeterministicLockStep = function () {
  100342. return this._options.deterministicLockstep;
  100343. };
  100344. NullEngine.prototype.getLockstepMaxSteps = function () {
  100345. return this._options.lockstepMaxSteps;
  100346. };
  100347. NullEngine.prototype.getHardwareScalingLevel = function () {
  100348. return 1.0;
  100349. };
  100350. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100351. return {
  100352. capacity: 0,
  100353. references: 1,
  100354. is32Bits: false
  100355. };
  100356. };
  100357. NullEngine.prototype.createIndexBuffer = function (indices) {
  100358. return {
  100359. capacity: 0,
  100360. references: 1,
  100361. is32Bits: false
  100362. };
  100363. };
  100364. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100365. if (stencil === void 0) { stencil = false; }
  100366. };
  100367. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100368. if (useScreen === void 0) { useScreen = false; }
  100369. if (!useScreen && this._currentRenderTarget) {
  100370. return this._currentRenderTarget.width;
  100371. }
  100372. return this._options.renderWidth;
  100373. };
  100374. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100375. if (useScreen === void 0) { useScreen = false; }
  100376. if (!useScreen && this._currentRenderTarget) {
  100377. return this._currentRenderTarget.height;
  100378. }
  100379. return this._options.renderHeight;
  100380. };
  100381. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100382. this._cachedViewport = viewport;
  100383. };
  100384. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100385. return {
  100386. transformFeedback: null,
  100387. __SPECTOR_rebuildProgram: null
  100388. };
  100389. };
  100390. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100391. return [];
  100392. };
  100393. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100394. return [];
  100395. };
  100396. NullEngine.prototype.bindSamplers = function (effect) {
  100397. this._currentEffect = null;
  100398. };
  100399. NullEngine.prototype.enableEffect = function (effect) {
  100400. this._currentEffect = effect;
  100401. if (effect.onBind) {
  100402. effect.onBind(effect);
  100403. }
  100404. effect.onBindObservable.notifyObservers(effect);
  100405. };
  100406. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100407. if (zOffset === void 0) { zOffset = 0; }
  100408. if (reverseSide === void 0) { reverseSide = false; }
  100409. };
  100410. NullEngine.prototype.setIntArray = function (uniform, array) {
  100411. };
  100412. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100413. };
  100414. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100415. };
  100416. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100417. };
  100418. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100419. };
  100420. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100421. };
  100422. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100423. };
  100424. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100425. };
  100426. NullEngine.prototype.setArray = function (uniform, array) {
  100427. };
  100428. NullEngine.prototype.setArray2 = function (uniform, array) {
  100429. };
  100430. NullEngine.prototype.setArray3 = function (uniform, array) {
  100431. };
  100432. NullEngine.prototype.setArray4 = function (uniform, array) {
  100433. };
  100434. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100435. };
  100436. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100437. };
  100438. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100439. };
  100440. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100441. };
  100442. NullEngine.prototype.setFloat = function (uniform, value) {
  100443. };
  100444. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100445. };
  100446. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100447. };
  100448. NullEngine.prototype.setBool = function (uniform, bool) {
  100449. };
  100450. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100451. };
  100452. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100453. };
  100454. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100455. };
  100456. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100457. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100458. if (this._alphaMode === mode) {
  100459. return;
  100460. }
  100461. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100462. if (!noDepthWriteChange) {
  100463. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100464. }
  100465. this._alphaMode = mode;
  100466. };
  100467. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100468. };
  100469. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100470. if (this.preventCacheWipeBetweenFrames) {
  100471. return;
  100472. }
  100473. this.resetTextureCache();
  100474. this._currentEffect = null;
  100475. if (bruteForce) {
  100476. this._currentProgram = null;
  100477. this._stencilState.reset();
  100478. this._depthCullingState.reset();
  100479. this._alphaState.reset();
  100480. }
  100481. this._cachedVertexBuffers = null;
  100482. this._cachedIndexBuffer = null;
  100483. this._cachedEffectForVertexBuffers = null;
  100484. };
  100485. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100486. };
  100487. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100488. };
  100489. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100490. };
  100491. NullEngine.prototype._createTexture = function () {
  100492. return {};
  100493. };
  100494. NullEngine.prototype._releaseTexture = function (texture) {
  100495. };
  100496. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100498. if (onLoad === void 0) { onLoad = null; }
  100499. if (onError === void 0) { onError = null; }
  100500. if (buffer === void 0) { buffer = null; }
  100501. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100502. var url = String(urlArg);
  100503. texture.url = url;
  100504. texture.generateMipMaps = !noMipmap;
  100505. texture.samplingMode = samplingMode;
  100506. texture.invertY = invertY;
  100507. texture.baseWidth = this._options.textureSize;
  100508. texture.baseHeight = this._options.textureSize;
  100509. texture.width = this._options.textureSize;
  100510. texture.height = this._options.textureSize;
  100511. if (format) {
  100512. texture.format = format;
  100513. }
  100514. texture.isReady = true;
  100515. if (onLoad) {
  100516. onLoad();
  100517. }
  100518. this._internalTexturesCache.push(texture);
  100519. return texture;
  100520. };
  100521. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100522. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100523. if (options !== undefined && typeof options === "object") {
  100524. fullOptions.generateMipMaps = options.generateMipMaps;
  100525. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100526. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100527. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100528. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100529. }
  100530. else {
  100531. fullOptions.generateMipMaps = options;
  100532. fullOptions.generateDepthBuffer = true;
  100533. fullOptions.generateStencilBuffer = false;
  100534. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100535. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100536. }
  100537. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100538. var width = size.width || size;
  100539. var height = size.height || size;
  100540. texture._depthStencilBuffer = {};
  100541. texture._framebuffer = {};
  100542. texture.baseWidth = width;
  100543. texture.baseHeight = height;
  100544. texture.width = width;
  100545. texture.height = height;
  100546. texture.isReady = true;
  100547. texture.samples = 1;
  100548. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100549. texture.samplingMode = fullOptions.samplingMode;
  100550. texture.type = fullOptions.type;
  100551. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100552. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100553. this._internalTexturesCache.push(texture);
  100554. return texture;
  100555. };
  100556. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100557. texture.samplingMode = samplingMode;
  100558. };
  100559. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100560. if (this._currentRenderTarget) {
  100561. this.unBindFramebuffer(this._currentRenderTarget);
  100562. }
  100563. this._currentRenderTarget = texture;
  100564. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100565. if (this._cachedViewport && !forceFullscreenViewport) {
  100566. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100567. }
  100568. };
  100569. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100570. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100571. this._currentRenderTarget = null;
  100572. if (onBeforeUnbind) {
  100573. if (texture._MSAAFramebuffer) {
  100574. this._currentFramebuffer = texture._framebuffer;
  100575. }
  100576. onBeforeUnbind();
  100577. }
  100578. this._currentFramebuffer = null;
  100579. };
  100580. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100581. var vbo = {
  100582. capacity: 1,
  100583. references: 1,
  100584. is32Bits: false
  100585. };
  100586. return vbo;
  100587. };
  100588. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100589. if (premulAlpha === void 0) { premulAlpha = false; }
  100590. };
  100591. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100592. if (offset === void 0) { offset = 0; }
  100593. };
  100594. /**
  100595. * Updates a dynamic vertex buffer.
  100596. * @param vertexBuffer the vertex buffer to update
  100597. * @param data the data used to update the vertex buffer
  100598. * @param byteOffset the byte offset of the data (optional)
  100599. * @param byteLength the byte length of the data (optional)
  100600. */
  100601. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100602. };
  100603. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100604. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100605. this._boundTexturesCache[this._activeChannel] = texture;
  100606. return true;
  100607. }
  100608. return false;
  100609. };
  100610. NullEngine.prototype._bindTexture = function (channel, texture) {
  100611. if (channel < 0) {
  100612. return;
  100613. }
  100614. this._bindTextureDirectly(0, texture);
  100615. };
  100616. NullEngine.prototype._releaseBuffer = function (buffer) {
  100617. buffer.references--;
  100618. if (buffer.references === 0) {
  100619. return true;
  100620. }
  100621. return false;
  100622. };
  100623. NullEngine.prototype.releaseEffects = function () {
  100624. };
  100625. NullEngine.prototype.displayLoadingUI = function () {
  100626. };
  100627. NullEngine.prototype.hideLoadingUI = function () {
  100628. };
  100629. return NullEngine;
  100630. }(BABYLON.Engine));
  100631. BABYLON.NullEngine = NullEngine;
  100632. })(BABYLON || (BABYLON = {}));
  100633. //# sourceMappingURL=babylon.nullEngine.js.map
  100634. var BABYLON;
  100635. (function (BABYLON) {
  100636. /**
  100637. * This class can be used to get instrumentation data from a Babylon engine
  100638. */
  100639. var EngineInstrumentation = /** @class */ (function () {
  100640. function EngineInstrumentation(engine) {
  100641. this.engine = engine;
  100642. this._captureGPUFrameTime = false;
  100643. this._gpuFrameTime = new BABYLON.PerfCounter();
  100644. this._captureShaderCompilationTime = false;
  100645. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100646. // Observers
  100647. this._onBeginFrameObserver = null;
  100648. this._onEndFrameObserver = null;
  100649. this._onBeforeShaderCompilationObserver = null;
  100650. this._onAfterShaderCompilationObserver = null;
  100651. }
  100652. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100653. // Properties
  100654. /**
  100655. * Gets the perf counter used for GPU frame time
  100656. */
  100657. get: function () {
  100658. return this._gpuFrameTime;
  100659. },
  100660. enumerable: true,
  100661. configurable: true
  100662. });
  100663. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100664. /**
  100665. * Gets the GPU frame time capture status
  100666. */
  100667. get: function () {
  100668. return this._captureGPUFrameTime;
  100669. },
  100670. /**
  100671. * Enable or disable the GPU frame time capture
  100672. */
  100673. set: function (value) {
  100674. var _this = this;
  100675. if (value === this._captureGPUFrameTime) {
  100676. return;
  100677. }
  100678. this._captureGPUFrameTime = value;
  100679. if (value) {
  100680. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100681. if (!_this._gpuFrameTimeToken) {
  100682. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100683. }
  100684. });
  100685. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100686. if (!_this._gpuFrameTimeToken) {
  100687. return;
  100688. }
  100689. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100690. if (time > -1) {
  100691. _this._gpuFrameTimeToken = null;
  100692. _this._gpuFrameTime.fetchNewFrame();
  100693. _this._gpuFrameTime.addCount(time, true);
  100694. }
  100695. });
  100696. }
  100697. else {
  100698. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100699. this._onBeginFrameObserver = null;
  100700. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100701. this._onEndFrameObserver = null;
  100702. }
  100703. },
  100704. enumerable: true,
  100705. configurable: true
  100706. });
  100707. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100708. /**
  100709. * Gets the perf counter used for shader compilation time
  100710. */
  100711. get: function () {
  100712. return this._shaderCompilationTime;
  100713. },
  100714. enumerable: true,
  100715. configurable: true
  100716. });
  100717. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100718. /**
  100719. * Gets the shader compilation time capture status
  100720. */
  100721. get: function () {
  100722. return this._captureShaderCompilationTime;
  100723. },
  100724. /**
  100725. * Enable or disable the shader compilation time capture
  100726. */
  100727. set: function (value) {
  100728. var _this = this;
  100729. if (value === this._captureShaderCompilationTime) {
  100730. return;
  100731. }
  100732. this._captureShaderCompilationTime = value;
  100733. if (value) {
  100734. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100735. _this._shaderCompilationTime.fetchNewFrame();
  100736. _this._shaderCompilationTime.beginMonitoring();
  100737. });
  100738. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100739. _this._shaderCompilationTime.endMonitoring();
  100740. });
  100741. }
  100742. else {
  100743. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100744. this._onBeforeShaderCompilationObserver = null;
  100745. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100746. this._onAfterShaderCompilationObserver = null;
  100747. }
  100748. },
  100749. enumerable: true,
  100750. configurable: true
  100751. });
  100752. EngineInstrumentation.prototype.dispose = function () {
  100753. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100754. this._onBeginFrameObserver = null;
  100755. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100756. this._onEndFrameObserver = null;
  100757. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100758. this._onBeforeShaderCompilationObserver = null;
  100759. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100760. this._onAfterShaderCompilationObserver = null;
  100761. this.engine = null;
  100762. };
  100763. return EngineInstrumentation;
  100764. }());
  100765. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100766. })(BABYLON || (BABYLON = {}));
  100767. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100768. var BABYLON;
  100769. (function (BABYLON) {
  100770. /**
  100771. * This class can be used to get instrumentation data from a Babylon engine
  100772. */
  100773. var SceneInstrumentation = /** @class */ (function () {
  100774. function SceneInstrumentation(scene) {
  100775. var _this = this;
  100776. this.scene = scene;
  100777. this._captureActiveMeshesEvaluationTime = false;
  100778. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100779. this._captureRenderTargetsRenderTime = false;
  100780. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100781. this._captureFrameTime = false;
  100782. this._frameTime = new BABYLON.PerfCounter();
  100783. this._captureRenderTime = false;
  100784. this._renderTime = new BABYLON.PerfCounter();
  100785. this._captureInterFrameTime = false;
  100786. this._interFrameTime = new BABYLON.PerfCounter();
  100787. this._captureParticlesRenderTime = false;
  100788. this._particlesRenderTime = new BABYLON.PerfCounter();
  100789. this._captureSpritesRenderTime = false;
  100790. this._spritesRenderTime = new BABYLON.PerfCounter();
  100791. this._capturePhysicsTime = false;
  100792. this._physicsTime = new BABYLON.PerfCounter();
  100793. this._captureAnimationsTime = false;
  100794. this._animationsTime = new BABYLON.PerfCounter();
  100795. this._captureCameraRenderTime = false;
  100796. this._cameraRenderTime = new BABYLON.PerfCounter();
  100797. // Observers
  100798. this._onBeforeActiveMeshesEvaluationObserver = null;
  100799. this._onAfterActiveMeshesEvaluationObserver = null;
  100800. this._onBeforeRenderTargetsRenderObserver = null;
  100801. this._onAfterRenderTargetsRenderObserver = null;
  100802. this._onAfterRenderObserver = null;
  100803. this._onBeforeDrawPhaseObserver = null;
  100804. this._onAfterDrawPhaseObserver = null;
  100805. this._onBeforeAnimationsObserver = null;
  100806. this._onBeforeParticlesRenderingObserver = null;
  100807. this._onAfterParticlesRenderingObserver = null;
  100808. this._onBeforeSpritesRenderingObserver = null;
  100809. this._onAfterSpritesRenderingObserver = null;
  100810. this._onBeforePhysicsObserver = null;
  100811. this._onAfterPhysicsObserver = null;
  100812. this._onAfterAnimationsObserver = null;
  100813. this._onBeforeCameraRenderObserver = null;
  100814. this._onAfterCameraRenderObserver = null;
  100815. // Before render
  100816. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100817. if (_this._captureActiveMeshesEvaluationTime) {
  100818. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100819. }
  100820. if (_this._captureRenderTargetsRenderTime) {
  100821. _this._renderTargetsRenderTime.fetchNewFrame();
  100822. }
  100823. if (_this._captureFrameTime) {
  100824. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100825. _this._frameTime.beginMonitoring();
  100826. }
  100827. if (_this._captureInterFrameTime) {
  100828. _this._interFrameTime.endMonitoring();
  100829. }
  100830. if (_this._captureParticlesRenderTime) {
  100831. _this._particlesRenderTime.fetchNewFrame();
  100832. }
  100833. if (_this._captureSpritesRenderTime) {
  100834. _this._spritesRenderTime.fetchNewFrame();
  100835. }
  100836. if (_this._captureAnimationsTime) {
  100837. _this._animationsTime.beginMonitoring();
  100838. }
  100839. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100840. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100841. });
  100842. // After render
  100843. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100844. if (_this._captureFrameTime) {
  100845. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100846. _this._frameTime.endMonitoring();
  100847. }
  100848. if (_this._captureRenderTime) {
  100849. _this._renderTime.endMonitoring(false);
  100850. }
  100851. if (_this._captureInterFrameTime) {
  100852. _this._interFrameTime.beginMonitoring();
  100853. }
  100854. });
  100855. }
  100856. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100857. // Properties
  100858. /**
  100859. * Gets the perf counter used for active meshes evaluation time
  100860. */
  100861. get: function () {
  100862. return this._activeMeshesEvaluationTime;
  100863. },
  100864. enumerable: true,
  100865. configurable: true
  100866. });
  100867. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100868. /**
  100869. * Gets the active meshes evaluation time capture status
  100870. */
  100871. get: function () {
  100872. return this._captureActiveMeshesEvaluationTime;
  100873. },
  100874. /**
  100875. * Enable or disable the active meshes evaluation time capture
  100876. */
  100877. set: function (value) {
  100878. var _this = this;
  100879. if (value === this._captureActiveMeshesEvaluationTime) {
  100880. return;
  100881. }
  100882. this._captureActiveMeshesEvaluationTime = value;
  100883. if (value) {
  100884. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100885. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100886. _this._activeMeshesEvaluationTime.beginMonitoring();
  100887. });
  100888. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100889. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100890. _this._activeMeshesEvaluationTime.endMonitoring();
  100891. });
  100892. }
  100893. else {
  100894. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100895. this._onBeforeActiveMeshesEvaluationObserver = null;
  100896. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100897. this._onAfterActiveMeshesEvaluationObserver = null;
  100898. }
  100899. },
  100900. enumerable: true,
  100901. configurable: true
  100902. });
  100903. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100904. /**
  100905. * Gets the perf counter used for render targets render time
  100906. */
  100907. get: function () {
  100908. return this._renderTargetsRenderTime;
  100909. },
  100910. enumerable: true,
  100911. configurable: true
  100912. });
  100913. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100914. /**
  100915. * Gets the render targets render time capture status
  100916. */
  100917. get: function () {
  100918. return this._captureRenderTargetsRenderTime;
  100919. },
  100920. /**
  100921. * Enable or disable the render targets render time capture
  100922. */
  100923. set: function (value) {
  100924. var _this = this;
  100925. if (value === this._captureRenderTargetsRenderTime) {
  100926. return;
  100927. }
  100928. this._captureRenderTargetsRenderTime = value;
  100929. if (value) {
  100930. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100931. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100932. _this._renderTargetsRenderTime.beginMonitoring();
  100933. });
  100934. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100935. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100936. _this._renderTargetsRenderTime.endMonitoring(false);
  100937. });
  100938. }
  100939. else {
  100940. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100941. this._onBeforeRenderTargetsRenderObserver = null;
  100942. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100943. this._onAfterRenderTargetsRenderObserver = null;
  100944. }
  100945. },
  100946. enumerable: true,
  100947. configurable: true
  100948. });
  100949. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100950. /**
  100951. * Gets the perf counter used for particles render time
  100952. */
  100953. get: function () {
  100954. return this._particlesRenderTime;
  100955. },
  100956. enumerable: true,
  100957. configurable: true
  100958. });
  100959. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100960. /**
  100961. * Gets the particles render time capture status
  100962. */
  100963. get: function () {
  100964. return this._captureParticlesRenderTime;
  100965. },
  100966. /**
  100967. * Enable or disable the particles render time capture
  100968. */
  100969. set: function (value) {
  100970. var _this = this;
  100971. if (value === this._captureParticlesRenderTime) {
  100972. return;
  100973. }
  100974. this._captureParticlesRenderTime = value;
  100975. if (value) {
  100976. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100977. BABYLON.Tools.StartPerformanceCounter("Particles");
  100978. _this._particlesRenderTime.beginMonitoring();
  100979. });
  100980. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100981. BABYLON.Tools.EndPerformanceCounter("Particles");
  100982. _this._particlesRenderTime.endMonitoring(false);
  100983. });
  100984. }
  100985. else {
  100986. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100987. this._onBeforeParticlesRenderingObserver = null;
  100988. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100989. this._onAfterParticlesRenderingObserver = null;
  100990. }
  100991. },
  100992. enumerable: true,
  100993. configurable: true
  100994. });
  100995. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100996. /**
  100997. * Gets the perf counter used for sprites render time
  100998. */
  100999. get: function () {
  101000. return this._spritesRenderTime;
  101001. },
  101002. enumerable: true,
  101003. configurable: true
  101004. });
  101005. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101006. /**
  101007. * Gets the sprites render time capture status
  101008. */
  101009. get: function () {
  101010. return this._captureSpritesRenderTime;
  101011. },
  101012. /**
  101013. * Enable or disable the sprites render time capture
  101014. */
  101015. set: function (value) {
  101016. var _this = this;
  101017. if (value === this._captureSpritesRenderTime) {
  101018. return;
  101019. }
  101020. this._captureSpritesRenderTime = value;
  101021. if (value) {
  101022. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101023. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101024. _this._spritesRenderTime.beginMonitoring();
  101025. });
  101026. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101027. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101028. _this._spritesRenderTime.endMonitoring(false);
  101029. });
  101030. }
  101031. else {
  101032. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101033. this._onBeforeSpritesRenderingObserver = null;
  101034. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101035. this._onAfterSpritesRenderingObserver = null;
  101036. }
  101037. },
  101038. enumerable: true,
  101039. configurable: true
  101040. });
  101041. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101042. /**
  101043. * Gets the perf counter used for physics time
  101044. */
  101045. get: function () {
  101046. return this._physicsTime;
  101047. },
  101048. enumerable: true,
  101049. configurable: true
  101050. });
  101051. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101052. /**
  101053. * Gets the physics time capture status
  101054. */
  101055. get: function () {
  101056. return this._capturePhysicsTime;
  101057. },
  101058. /**
  101059. * Enable or disable the physics time capture
  101060. */
  101061. set: function (value) {
  101062. var _this = this;
  101063. if (value === this._capturePhysicsTime) {
  101064. return;
  101065. }
  101066. this._capturePhysicsTime = value;
  101067. if (value) {
  101068. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101069. BABYLON.Tools.StartPerformanceCounter("Physics");
  101070. _this._physicsTime.beginMonitoring();
  101071. });
  101072. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101073. BABYLON.Tools.EndPerformanceCounter("Physics");
  101074. _this._physicsTime.endMonitoring();
  101075. });
  101076. }
  101077. else {
  101078. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101079. this._onBeforePhysicsObserver = null;
  101080. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101081. this._onAfterPhysicsObserver = null;
  101082. }
  101083. },
  101084. enumerable: true,
  101085. configurable: true
  101086. });
  101087. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101088. /**
  101089. * Gets the perf counter used for animations time
  101090. */
  101091. get: function () {
  101092. return this._animationsTime;
  101093. },
  101094. enumerable: true,
  101095. configurable: true
  101096. });
  101097. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101098. /**
  101099. * Gets the animations time capture status
  101100. */
  101101. get: function () {
  101102. return this._captureAnimationsTime;
  101103. },
  101104. /**
  101105. * Enable or disable the animations time capture
  101106. */
  101107. set: function (value) {
  101108. var _this = this;
  101109. if (value === this._captureAnimationsTime) {
  101110. return;
  101111. }
  101112. this._captureAnimationsTime = value;
  101113. if (value) {
  101114. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101115. _this._animationsTime.endMonitoring();
  101116. });
  101117. }
  101118. else {
  101119. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101120. this._onAfterAnimationsObserver = null;
  101121. }
  101122. },
  101123. enumerable: true,
  101124. configurable: true
  101125. });
  101126. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101127. /**
  101128. * Gets the perf counter used for frame time capture
  101129. */
  101130. get: function () {
  101131. return this._frameTime;
  101132. },
  101133. enumerable: true,
  101134. configurable: true
  101135. });
  101136. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101137. /**
  101138. * Gets the frame time capture status
  101139. */
  101140. get: function () {
  101141. return this._captureFrameTime;
  101142. },
  101143. /**
  101144. * Enable or disable the frame time capture
  101145. */
  101146. set: function (value) {
  101147. this._captureFrameTime = value;
  101148. },
  101149. enumerable: true,
  101150. configurable: true
  101151. });
  101152. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101153. /**
  101154. * Gets the perf counter used for inter-frames time capture
  101155. */
  101156. get: function () {
  101157. return this._interFrameTime;
  101158. },
  101159. enumerable: true,
  101160. configurable: true
  101161. });
  101162. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101163. /**
  101164. * Gets the inter-frames time capture status
  101165. */
  101166. get: function () {
  101167. return this._captureInterFrameTime;
  101168. },
  101169. /**
  101170. * Enable or disable the inter-frames time capture
  101171. */
  101172. set: function (value) {
  101173. this._captureInterFrameTime = value;
  101174. },
  101175. enumerable: true,
  101176. configurable: true
  101177. });
  101178. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101179. /**
  101180. * Gets the perf counter used for render time capture
  101181. */
  101182. get: function () {
  101183. return this._renderTime;
  101184. },
  101185. enumerable: true,
  101186. configurable: true
  101187. });
  101188. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101189. /**
  101190. * Gets the render time capture status
  101191. */
  101192. get: function () {
  101193. return this._captureRenderTime;
  101194. },
  101195. /**
  101196. * Enable or disable the render time capture
  101197. */
  101198. set: function (value) {
  101199. var _this = this;
  101200. if (value === this._captureRenderTime) {
  101201. return;
  101202. }
  101203. this._captureRenderTime = value;
  101204. if (value) {
  101205. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101206. _this._renderTime.beginMonitoring();
  101207. BABYLON.Tools.StartPerformanceCounter("Main render");
  101208. });
  101209. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101210. _this._renderTime.endMonitoring(false);
  101211. BABYLON.Tools.EndPerformanceCounter("Main render");
  101212. });
  101213. }
  101214. else {
  101215. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101216. this._onBeforeDrawPhaseObserver = null;
  101217. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101218. this._onAfterDrawPhaseObserver = null;
  101219. }
  101220. },
  101221. enumerable: true,
  101222. configurable: true
  101223. });
  101224. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101225. /**
  101226. * Gets the perf counter used for camera render time capture
  101227. */
  101228. get: function () {
  101229. return this._cameraRenderTime;
  101230. },
  101231. enumerable: true,
  101232. configurable: true
  101233. });
  101234. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101235. /**
  101236. * Gets the camera render time capture status
  101237. */
  101238. get: function () {
  101239. return this._captureCameraRenderTime;
  101240. },
  101241. /**
  101242. * Enable or disable the camera render time capture
  101243. */
  101244. set: function (value) {
  101245. var _this = this;
  101246. if (value === this._captureCameraRenderTime) {
  101247. return;
  101248. }
  101249. this._captureCameraRenderTime = value;
  101250. if (value) {
  101251. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101252. _this._cameraRenderTime.beginMonitoring();
  101253. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101254. });
  101255. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101256. _this._cameraRenderTime.endMonitoring(false);
  101257. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101258. });
  101259. }
  101260. else {
  101261. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101262. this._onBeforeCameraRenderObserver = null;
  101263. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101264. this._onAfterCameraRenderObserver = null;
  101265. }
  101266. },
  101267. enumerable: true,
  101268. configurable: true
  101269. });
  101270. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101271. /**
  101272. * Gets the perf counter used for draw calls
  101273. */
  101274. get: function () {
  101275. return this.scene.getEngine()._drawCalls;
  101276. },
  101277. enumerable: true,
  101278. configurable: true
  101279. });
  101280. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101281. /**
  101282. * Gets the perf counter used for texture collisions
  101283. */
  101284. get: function () {
  101285. return this.scene.getEngine()._textureCollisions;
  101286. },
  101287. enumerable: true,
  101288. configurable: true
  101289. });
  101290. SceneInstrumentation.prototype.dispose = function () {
  101291. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101292. this._onAfterRenderObserver = null;
  101293. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101294. this._onBeforeActiveMeshesEvaluationObserver = null;
  101295. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101296. this._onAfterActiveMeshesEvaluationObserver = null;
  101297. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101298. this._onBeforeRenderTargetsRenderObserver = null;
  101299. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101300. this._onAfterRenderTargetsRenderObserver = null;
  101301. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101302. this._onBeforeAnimationsObserver = null;
  101303. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101304. this._onBeforeParticlesRenderingObserver = null;
  101305. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101306. this._onAfterParticlesRenderingObserver = null;
  101307. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101308. this._onBeforeSpritesRenderingObserver = null;
  101309. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101310. this._onAfterSpritesRenderingObserver = null;
  101311. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101312. this._onBeforeDrawPhaseObserver = null;
  101313. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101314. this._onAfterDrawPhaseObserver = null;
  101315. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101316. this._onBeforePhysicsObserver = null;
  101317. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101318. this._onAfterPhysicsObserver = null;
  101319. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101320. this._onAfterAnimationsObserver = null;
  101321. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101322. this._onBeforeCameraRenderObserver = null;
  101323. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101324. this._onAfterCameraRenderObserver = null;
  101325. this.scene = null;
  101326. };
  101327. return SceneInstrumentation;
  101328. }());
  101329. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101330. })(BABYLON || (BABYLON = {}));
  101331. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101332. var BABYLON;
  101333. (function (BABYLON) {
  101334. /**
  101335. * @hidden
  101336. **/
  101337. var _TimeToken = /** @class */ (function () {
  101338. function _TimeToken() {
  101339. this._timeElapsedQueryEnded = false;
  101340. }
  101341. return _TimeToken;
  101342. }());
  101343. BABYLON._TimeToken = _TimeToken;
  101344. })(BABYLON || (BABYLON = {}));
  101345. //# sourceMappingURL=babylon.timeToken.js.map
  101346. var BABYLON;
  101347. (function (BABYLON) {
  101348. /**
  101349. * Background material defines definition.
  101350. * @hidden Mainly internal Use
  101351. */
  101352. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101353. __extends(BackgroundMaterialDefines, _super);
  101354. /**
  101355. * Constructor of the defines.
  101356. */
  101357. function BackgroundMaterialDefines() {
  101358. var _this = _super.call(this) || this;
  101359. /**
  101360. * True if the diffuse texture is in use.
  101361. */
  101362. _this.DIFFUSE = false;
  101363. /**
  101364. * The direct UV channel to use.
  101365. */
  101366. _this.DIFFUSEDIRECTUV = 0;
  101367. /**
  101368. * True if the diffuse texture is in gamma space.
  101369. */
  101370. _this.GAMMADIFFUSE = false;
  101371. /**
  101372. * True if the diffuse texture has opacity in the alpha channel.
  101373. */
  101374. _this.DIFFUSEHASALPHA = false;
  101375. /**
  101376. * True if you want the material to fade to transparent at grazing angle.
  101377. */
  101378. _this.OPACITYFRESNEL = false;
  101379. /**
  101380. * True if an extra blur needs to be added in the reflection.
  101381. */
  101382. _this.REFLECTIONBLUR = false;
  101383. /**
  101384. * True if you want the material to fade to reflection at grazing angle.
  101385. */
  101386. _this.REFLECTIONFRESNEL = false;
  101387. /**
  101388. * True if you want the material to falloff as far as you move away from the scene center.
  101389. */
  101390. _this.REFLECTIONFALLOFF = false;
  101391. /**
  101392. * False if the current Webgl implementation does not support the texture lod extension.
  101393. */
  101394. _this.TEXTURELODSUPPORT = false;
  101395. /**
  101396. * True to ensure the data are premultiplied.
  101397. */
  101398. _this.PREMULTIPLYALPHA = false;
  101399. /**
  101400. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101401. */
  101402. _this.USERGBCOLOR = false;
  101403. /**
  101404. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101405. * stays aligned with the desired configuration.
  101406. */
  101407. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101408. /**
  101409. * True to add noise in order to reduce the banding effect.
  101410. */
  101411. _this.NOISE = false;
  101412. /**
  101413. * is the reflection texture in BGR color scheme?
  101414. * Mainly used to solve a bug in ios10 video tag
  101415. */
  101416. _this.REFLECTIONBGR = false;
  101417. _this.IMAGEPROCESSING = false;
  101418. _this.VIGNETTE = false;
  101419. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101420. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101421. _this.TONEMAPPING = false;
  101422. _this.CONTRAST = false;
  101423. _this.COLORCURVES = false;
  101424. _this.COLORGRADING = false;
  101425. _this.COLORGRADING3D = false;
  101426. _this.SAMPLER3DGREENDEPTH = false;
  101427. _this.SAMPLER3DBGRMAP = false;
  101428. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101429. _this.EXPOSURE = false;
  101430. // Reflection.
  101431. _this.REFLECTION = false;
  101432. _this.REFLECTIONMAP_3D = false;
  101433. _this.REFLECTIONMAP_SPHERICAL = false;
  101434. _this.REFLECTIONMAP_PLANAR = false;
  101435. _this.REFLECTIONMAP_CUBIC = false;
  101436. _this.REFLECTIONMAP_PROJECTION = false;
  101437. _this.REFLECTIONMAP_SKYBOX = false;
  101438. _this.REFLECTIONMAP_EXPLICIT = false;
  101439. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101440. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101441. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101442. _this.INVERTCUBICMAP = false;
  101443. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101444. _this.LODINREFLECTIONALPHA = false;
  101445. _this.GAMMAREFLECTION = false;
  101446. _this.RGBDREFLECTION = false;
  101447. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101448. // Default BJS.
  101449. _this.MAINUV1 = false;
  101450. _this.MAINUV2 = false;
  101451. _this.UV1 = false;
  101452. _this.UV2 = false;
  101453. _this.CLIPPLANE = false;
  101454. _this.POINTSIZE = false;
  101455. _this.FOG = false;
  101456. _this.NORMAL = false;
  101457. _this.NUM_BONE_INFLUENCERS = 0;
  101458. _this.BonesPerMesh = 0;
  101459. _this.INSTANCES = false;
  101460. _this.SHADOWFLOAT = false;
  101461. _this.rebuild();
  101462. return _this;
  101463. }
  101464. return BackgroundMaterialDefines;
  101465. }(BABYLON.MaterialDefines));
  101466. /**
  101467. * Background material used to create an efficient environement around your scene.
  101468. */
  101469. var BackgroundMaterial = /** @class */ (function (_super) {
  101470. __extends(BackgroundMaterial, _super);
  101471. /**
  101472. * Instantiates a Background Material in the given scene
  101473. * @param name The friendly name of the material
  101474. * @param scene The scene to add the material to
  101475. */
  101476. function BackgroundMaterial(name, scene) {
  101477. var _this = _super.call(this, name, scene) || this;
  101478. /**
  101479. * Key light Color (multiply against the environement texture)
  101480. */
  101481. _this.primaryColor = BABYLON.Color3.White();
  101482. _this._primaryColorShadowLevel = 0;
  101483. _this._primaryColorHighlightLevel = 0;
  101484. /**
  101485. * Reflection Texture used in the material.
  101486. * Should be author in a specific way for the best result (refer to the documentation).
  101487. */
  101488. _this.reflectionTexture = null;
  101489. /**
  101490. * Reflection Texture level of blur.
  101491. *
  101492. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101493. * texture twice.
  101494. */
  101495. _this.reflectionBlur = 0;
  101496. /**
  101497. * Diffuse Texture used in the material.
  101498. * Should be author in a specific way for the best result (refer to the documentation).
  101499. */
  101500. _this.diffuseTexture = null;
  101501. _this._shadowLights = null;
  101502. /**
  101503. * Specify the list of lights casting shadow on the material.
  101504. * All scene shadow lights will be included if null.
  101505. */
  101506. _this.shadowLights = null;
  101507. /**
  101508. * Helps adjusting the shadow to a softer level if required.
  101509. * 0 means black shadows and 1 means no shadows.
  101510. */
  101511. _this.shadowLevel = 0;
  101512. /**
  101513. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101514. * It is usually zero but might be interesting to modify according to your setup.
  101515. */
  101516. _this.sceneCenter = BABYLON.Vector3.Zero();
  101517. /**
  101518. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101519. * This helps ensuring a nice transition when the camera goes under the ground.
  101520. */
  101521. _this.opacityFresnel = true;
  101522. /**
  101523. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101524. * This helps adding a mirror texture on the ground.
  101525. */
  101526. _this.reflectionFresnel = false;
  101527. /**
  101528. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101529. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101530. */
  101531. _this.reflectionFalloffDistance = 0.0;
  101532. /**
  101533. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101534. */
  101535. _this.reflectionAmount = 1.0;
  101536. /**
  101537. * This specifies the weight of the reflection at grazing angle.
  101538. */
  101539. _this.reflectionReflectance0 = 0.05;
  101540. /**
  101541. * This specifies the weight of the reflection at a perpendicular point of view.
  101542. */
  101543. _this.reflectionReflectance90 = 0.5;
  101544. /**
  101545. * Helps to directly use the maps channels instead of their level.
  101546. */
  101547. _this.useRGBColor = true;
  101548. /**
  101549. * This helps reducing the banding effect that could occur on the background.
  101550. */
  101551. _this.enableNoise = false;
  101552. _this._fovMultiplier = 1.0;
  101553. /**
  101554. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101555. */
  101556. _this.useEquirectangularFOV = false;
  101557. _this._maxSimultaneousLights = 4;
  101558. /**
  101559. * Number of Simultaneous lights allowed on the material.
  101560. */
  101561. _this.maxSimultaneousLights = 4;
  101562. /**
  101563. * Keep track of the image processing observer to allow dispose and replace.
  101564. */
  101565. _this._imageProcessingObserver = null;
  101566. /**
  101567. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101568. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101569. */
  101570. _this.switchToBGR = false;
  101571. // Temp values kept as cache in the material.
  101572. _this._renderTargets = new BABYLON.SmartArray(16);
  101573. _this._reflectionControls = BABYLON.Vector4.Zero();
  101574. _this._white = BABYLON.Color3.White();
  101575. _this._primaryShadowColor = BABYLON.Color3.Black();
  101576. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101577. // Setup the default processing configuration to the scene.
  101578. _this._attachImageProcessingConfiguration(null);
  101579. _this.getRenderTargetTextures = function () {
  101580. _this._renderTargets.reset();
  101581. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101582. _this._renderTargets.push(_this._diffuseTexture);
  101583. }
  101584. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101585. _this._renderTargets.push(_this._reflectionTexture);
  101586. }
  101587. return _this._renderTargets;
  101588. };
  101589. return _this;
  101590. }
  101591. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101592. /**
  101593. * Experimental Internal Use Only.
  101594. *
  101595. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101596. * This acts as a helper to set the primary color to a more "human friendly" value.
  101597. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101598. * output color as close as possible from the chosen value.
  101599. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101600. * part of lighting setup.)
  101601. */
  101602. get: function () {
  101603. return this.__perceptualColor;
  101604. },
  101605. set: function (value) {
  101606. this.__perceptualColor = value;
  101607. this._computePrimaryColorFromPerceptualColor();
  101608. this._markAllSubMeshesAsLightsDirty();
  101609. },
  101610. enumerable: true,
  101611. configurable: true
  101612. });
  101613. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101614. /**
  101615. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101616. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101617. */
  101618. get: function () {
  101619. return this._primaryColorShadowLevel;
  101620. },
  101621. set: function (value) {
  101622. this._primaryColorShadowLevel = value;
  101623. this._computePrimaryColors();
  101624. this._markAllSubMeshesAsLightsDirty();
  101625. },
  101626. enumerable: true,
  101627. configurable: true
  101628. });
  101629. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101630. /**
  101631. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101632. * The primary color is used at the level chosen to define what the white area would look.
  101633. */
  101634. get: function () {
  101635. return this._primaryColorHighlightLevel;
  101636. },
  101637. set: function (value) {
  101638. this._primaryColorHighlightLevel = value;
  101639. this._computePrimaryColors();
  101640. this._markAllSubMeshesAsLightsDirty();
  101641. },
  101642. enumerable: true,
  101643. configurable: true
  101644. });
  101645. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101646. /**
  101647. * Sets the reflection reflectance fresnel values according to the default standard
  101648. * empirically know to work well :-)
  101649. */
  101650. set: function (value) {
  101651. var reflectionWeight = value;
  101652. if (reflectionWeight < 0.5) {
  101653. reflectionWeight = reflectionWeight * 2.0;
  101654. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101655. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101656. }
  101657. else {
  101658. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101659. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101660. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101661. }
  101662. },
  101663. enumerable: true,
  101664. configurable: true
  101665. });
  101666. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101667. /**
  101668. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101669. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101670. * Recommended to be keep at 1.0 except for special cases.
  101671. */
  101672. get: function () {
  101673. return this._fovMultiplier;
  101674. },
  101675. set: function (value) {
  101676. if (isNaN(value)) {
  101677. value = 1.0;
  101678. }
  101679. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101680. },
  101681. enumerable: true,
  101682. configurable: true
  101683. });
  101684. /**
  101685. * Attaches a new image processing configuration to the PBR Material.
  101686. * @param configuration (if null the scene configuration will be use)
  101687. */
  101688. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101689. var _this = this;
  101690. if (configuration === this._imageProcessingConfiguration) {
  101691. return;
  101692. }
  101693. // Detaches observer.
  101694. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101695. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101696. }
  101697. // Pick the scene configuration if needed.
  101698. if (!configuration) {
  101699. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101700. }
  101701. else {
  101702. this._imageProcessingConfiguration = configuration;
  101703. }
  101704. // Attaches observer.
  101705. if (this._imageProcessingConfiguration) {
  101706. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101707. _this._computePrimaryColorFromPerceptualColor();
  101708. _this._markAllSubMeshesAsImageProcessingDirty();
  101709. });
  101710. }
  101711. };
  101712. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101713. /**
  101714. * Gets the image processing configuration used either in this material.
  101715. */
  101716. get: function () {
  101717. return this._imageProcessingConfiguration;
  101718. },
  101719. /**
  101720. * Sets the Default image processing configuration used either in the this material.
  101721. *
  101722. * If sets to null, the scene one is in use.
  101723. */
  101724. set: function (value) {
  101725. this._attachImageProcessingConfiguration(value);
  101726. // Ensure the effect will be rebuilt.
  101727. this._markAllSubMeshesAsTexturesDirty();
  101728. },
  101729. enumerable: true,
  101730. configurable: true
  101731. });
  101732. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101733. /**
  101734. * Gets wether the color curves effect is enabled.
  101735. */
  101736. get: function () {
  101737. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101738. },
  101739. /**
  101740. * Sets wether the color curves effect is enabled.
  101741. */
  101742. set: function (value) {
  101743. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101744. },
  101745. enumerable: true,
  101746. configurable: true
  101747. });
  101748. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101749. /**
  101750. * Gets wether the color grading effect is enabled.
  101751. */
  101752. get: function () {
  101753. return this.imageProcessingConfiguration.colorGradingEnabled;
  101754. },
  101755. /**
  101756. * Gets wether the color grading effect is enabled.
  101757. */
  101758. set: function (value) {
  101759. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101760. },
  101761. enumerable: true,
  101762. configurable: true
  101763. });
  101764. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101765. /**
  101766. * Gets wether tonemapping is enabled or not.
  101767. */
  101768. get: function () {
  101769. return this._imageProcessingConfiguration.toneMappingEnabled;
  101770. },
  101771. /**
  101772. * Sets wether tonemapping is enabled or not
  101773. */
  101774. set: function (value) {
  101775. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101776. },
  101777. enumerable: true,
  101778. configurable: true
  101779. });
  101780. ;
  101781. ;
  101782. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101783. /**
  101784. * The camera exposure used on this material.
  101785. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101786. * This corresponds to a photographic exposure.
  101787. */
  101788. get: function () {
  101789. return this._imageProcessingConfiguration.exposure;
  101790. },
  101791. /**
  101792. * The camera exposure used on this material.
  101793. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101794. * This corresponds to a photographic exposure.
  101795. */
  101796. set: function (value) {
  101797. this._imageProcessingConfiguration.exposure = value;
  101798. },
  101799. enumerable: true,
  101800. configurable: true
  101801. });
  101802. ;
  101803. ;
  101804. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101805. /**
  101806. * Gets The camera contrast used on this material.
  101807. */
  101808. get: function () {
  101809. return this._imageProcessingConfiguration.contrast;
  101810. },
  101811. /**
  101812. * Sets The camera contrast used on this material.
  101813. */
  101814. set: function (value) {
  101815. this._imageProcessingConfiguration.contrast = value;
  101816. },
  101817. enumerable: true,
  101818. configurable: true
  101819. });
  101820. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101821. /**
  101822. * Gets the Color Grading 2D Lookup Texture.
  101823. */
  101824. get: function () {
  101825. return this._imageProcessingConfiguration.colorGradingTexture;
  101826. },
  101827. /**
  101828. * Sets the Color Grading 2D Lookup Texture.
  101829. */
  101830. set: function (value) {
  101831. this.imageProcessingConfiguration.colorGradingTexture = value;
  101832. },
  101833. enumerable: true,
  101834. configurable: true
  101835. });
  101836. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101837. /**
  101838. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101839. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101840. * 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;
  101841. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101842. */
  101843. get: function () {
  101844. return this.imageProcessingConfiguration.colorCurves;
  101845. },
  101846. /**
  101847. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101848. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101849. * 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;
  101850. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101851. */
  101852. set: function (value) {
  101853. this.imageProcessingConfiguration.colorCurves = value;
  101854. },
  101855. enumerable: true,
  101856. configurable: true
  101857. });
  101858. /**
  101859. * The entire material has been created in order to prevent overdraw.
  101860. * @returns false
  101861. */
  101862. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101863. return true;
  101864. };
  101865. /**
  101866. * The entire material has been created in order to prevent overdraw.
  101867. * @returns true if blending is enable
  101868. */
  101869. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101870. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101871. };
  101872. /**
  101873. * Checks wether the material is ready to be rendered for a given mesh.
  101874. * @param mesh The mesh to render
  101875. * @param subMesh The submesh to check against
  101876. * @param useInstances Specify wether or not the material is used with instances
  101877. * @returns true if all the dependencies are ready (Textures, Effects...)
  101878. */
  101879. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101880. var _this = this;
  101881. if (useInstances === void 0) { useInstances = false; }
  101882. if (subMesh.effect && this.isFrozen) {
  101883. if (this._wasPreviouslyReady) {
  101884. return true;
  101885. }
  101886. }
  101887. if (!subMesh._materialDefines) {
  101888. subMesh._materialDefines = new BackgroundMaterialDefines();
  101889. }
  101890. var scene = this.getScene();
  101891. var defines = subMesh._materialDefines;
  101892. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101893. if (defines._renderId === scene.getRenderId()) {
  101894. return true;
  101895. }
  101896. }
  101897. var engine = scene.getEngine();
  101898. // Lights
  101899. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101900. defines._needNormals = true;
  101901. // Textures
  101902. if (defines._areTexturesDirty) {
  101903. defines._needUVs = false;
  101904. if (scene.texturesEnabled) {
  101905. if (scene.getEngine().getCaps().textureLOD) {
  101906. defines.TEXTURELODSUPPORT = true;
  101907. }
  101908. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101909. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101910. return false;
  101911. }
  101912. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101913. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101914. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101915. defines.OPACITYFRESNEL = this._opacityFresnel;
  101916. }
  101917. else {
  101918. defines.DIFFUSE = false;
  101919. defines.DIFFUSEHASALPHA = false;
  101920. defines.GAMMADIFFUSE = false;
  101921. defines.OPACITYFRESNEL = false;
  101922. }
  101923. var reflectionTexture = this._reflectionTexture;
  101924. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101925. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101926. return false;
  101927. }
  101928. defines.REFLECTION = true;
  101929. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101930. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101931. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101932. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101933. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101934. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101935. defines.REFLECTIONBGR = this.switchToBGR;
  101936. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101937. defines.INVERTCUBICMAP = true;
  101938. }
  101939. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101940. switch (reflectionTexture.coordinatesMode) {
  101941. case BABYLON.Texture.EXPLICIT_MODE:
  101942. defines.REFLECTIONMAP_EXPLICIT = true;
  101943. break;
  101944. case BABYLON.Texture.PLANAR_MODE:
  101945. defines.REFLECTIONMAP_PLANAR = true;
  101946. break;
  101947. case BABYLON.Texture.PROJECTION_MODE:
  101948. defines.REFLECTIONMAP_PROJECTION = true;
  101949. break;
  101950. case BABYLON.Texture.SKYBOX_MODE:
  101951. defines.REFLECTIONMAP_SKYBOX = true;
  101952. break;
  101953. case BABYLON.Texture.SPHERICAL_MODE:
  101954. defines.REFLECTIONMAP_SPHERICAL = true;
  101955. break;
  101956. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101957. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101958. break;
  101959. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101960. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101961. break;
  101962. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101963. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101964. break;
  101965. case BABYLON.Texture.CUBIC_MODE:
  101966. case BABYLON.Texture.INVCUBIC_MODE:
  101967. default:
  101968. defines.REFLECTIONMAP_CUBIC = true;
  101969. break;
  101970. }
  101971. if (this.reflectionFresnel) {
  101972. defines.REFLECTIONFRESNEL = true;
  101973. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101974. this._reflectionControls.x = this.reflectionAmount;
  101975. this._reflectionControls.y = this.reflectionReflectance0;
  101976. this._reflectionControls.z = this.reflectionReflectance90;
  101977. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101978. }
  101979. else {
  101980. defines.REFLECTIONFRESNEL = false;
  101981. defines.REFLECTIONFALLOFF = false;
  101982. }
  101983. }
  101984. else {
  101985. defines.REFLECTION = false;
  101986. defines.REFLECTIONFRESNEL = false;
  101987. defines.REFLECTIONFALLOFF = false;
  101988. defines.REFLECTIONBLUR = false;
  101989. defines.REFLECTIONMAP_3D = false;
  101990. defines.REFLECTIONMAP_SPHERICAL = false;
  101991. defines.REFLECTIONMAP_PLANAR = false;
  101992. defines.REFLECTIONMAP_CUBIC = false;
  101993. defines.REFLECTIONMAP_PROJECTION = false;
  101994. defines.REFLECTIONMAP_SKYBOX = false;
  101995. defines.REFLECTIONMAP_EXPLICIT = false;
  101996. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101997. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101998. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101999. defines.INVERTCUBICMAP = false;
  102000. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102001. defines.LODINREFLECTIONALPHA = false;
  102002. defines.GAMMAREFLECTION = false;
  102003. defines.RGBDREFLECTION = false;
  102004. }
  102005. }
  102006. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102007. defines.USERGBCOLOR = this._useRGBColor;
  102008. defines.NOISE = this._enableNoise;
  102009. }
  102010. if (defines._areLightsDirty) {
  102011. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102012. }
  102013. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102014. if (!this._imageProcessingConfiguration.isReady()) {
  102015. return false;
  102016. }
  102017. this._imageProcessingConfiguration.prepareDefines(defines);
  102018. }
  102019. // Misc.
  102020. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102021. // Values that need to be evaluated on every frame
  102022. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102023. // Attribs
  102024. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102025. if (mesh) {
  102026. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102027. mesh.createNormals(true);
  102028. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102029. }
  102030. }
  102031. }
  102032. // Get correct effect
  102033. if (defines.isDirty) {
  102034. defines.markAsProcessed();
  102035. scene.resetCachedMaterial();
  102036. // Fallbacks
  102037. var fallbacks = new BABYLON.EffectFallbacks();
  102038. if (defines.FOG) {
  102039. fallbacks.addFallback(0, "FOG");
  102040. }
  102041. if (defines.POINTSIZE) {
  102042. fallbacks.addFallback(1, "POINTSIZE");
  102043. }
  102044. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102045. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102046. fallbacks.addCPUSkinningFallback(0, mesh);
  102047. }
  102048. //Attributes
  102049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102050. if (defines.NORMAL) {
  102051. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102052. }
  102053. if (defines.UV1) {
  102054. attribs.push(BABYLON.VertexBuffer.UVKind);
  102055. }
  102056. if (defines.UV2) {
  102057. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102058. }
  102059. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102060. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102061. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102062. "vFogInfos", "vFogColor", "pointSize",
  102063. "vClipPlane", "mBones",
  102064. "vPrimaryColor", "vPrimaryColorShadow",
  102065. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102066. "shadowLevel", "alpha",
  102067. "vBackgroundCenter", "vReflectionControl",
  102068. "vDiffuseInfos", "diffuseMatrix",
  102069. ];
  102070. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102071. var uniformBuffers = ["Material", "Scene"];
  102072. if (BABYLON.ImageProcessingConfiguration) {
  102073. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102074. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102075. }
  102076. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102077. uniformsNames: uniforms,
  102078. uniformBuffersNames: uniformBuffers,
  102079. samplers: samplers,
  102080. defines: defines,
  102081. maxSimultaneousLights: this._maxSimultaneousLights
  102082. });
  102083. var onCompiled = function (effect) {
  102084. if (_this.onCompiled) {
  102085. _this.onCompiled(effect);
  102086. }
  102087. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102088. };
  102089. var join = defines.toString();
  102090. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102091. attributes: attribs,
  102092. uniformsNames: uniforms,
  102093. uniformBuffersNames: uniformBuffers,
  102094. samplers: samplers,
  102095. defines: join,
  102096. fallbacks: fallbacks,
  102097. onCompiled: onCompiled,
  102098. onError: this.onError,
  102099. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102100. }, engine), defines);
  102101. this.buildUniformLayout();
  102102. }
  102103. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102104. return false;
  102105. }
  102106. defines._renderId = scene.getRenderId();
  102107. this._wasPreviouslyReady = true;
  102108. return true;
  102109. };
  102110. /**
  102111. * Compute the primary color according to the chosen perceptual color.
  102112. */
  102113. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102114. if (!this.__perceptualColor) {
  102115. return;
  102116. }
  102117. this._primaryColor.copyFrom(this.__perceptualColor);
  102118. // Revert gamma space.
  102119. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102120. // Revert image processing configuration.
  102121. if (this._imageProcessingConfiguration) {
  102122. // Revert Exposure.
  102123. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102124. }
  102125. this._computePrimaryColors();
  102126. };
  102127. /**
  102128. * Compute the highlights and shadow colors according to their chosen levels.
  102129. */
  102130. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102131. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102132. return;
  102133. }
  102134. // Find the highlight color based on the configuration.
  102135. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102136. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102137. // Find the shadow color based on the configuration.
  102138. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102139. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102140. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102141. };
  102142. /**
  102143. * Build the uniform buffer used in the material.
  102144. */
  102145. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102146. // Order is important !
  102147. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102148. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102149. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102150. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102151. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102152. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102153. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102154. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102155. this._uniformBuffer.addUniform("pointSize", 1);
  102156. this._uniformBuffer.addUniform("shadowLevel", 1);
  102157. this._uniformBuffer.addUniform("alpha", 1);
  102158. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102159. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102160. this._uniformBuffer.create();
  102161. };
  102162. /**
  102163. * Unbind the material.
  102164. */
  102165. BackgroundMaterial.prototype.unbind = function () {
  102166. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102167. this._uniformBuffer.setTexture("diffuseSampler", null);
  102168. }
  102169. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102170. this._uniformBuffer.setTexture("reflectionSampler", null);
  102171. }
  102172. _super.prototype.unbind.call(this);
  102173. };
  102174. /**
  102175. * Bind only the world matrix to the material.
  102176. * @param world The world matrix to bind.
  102177. */
  102178. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102179. this._activeEffect.setMatrix("world", world);
  102180. };
  102181. /**
  102182. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102183. * @param world The world matrix to bind.
  102184. * @param subMesh The submesh to bind for.
  102185. */
  102186. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102187. var scene = this.getScene();
  102188. var defines = subMesh._materialDefines;
  102189. if (!defines) {
  102190. return;
  102191. }
  102192. var effect = subMesh.effect;
  102193. if (!effect) {
  102194. return;
  102195. }
  102196. this._activeEffect = effect;
  102197. // Matrices
  102198. this.bindOnlyWorldMatrix(world);
  102199. // Bones
  102200. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102201. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102202. if (mustRebind) {
  102203. this._uniformBuffer.bindToEffect(effect, "Material");
  102204. this.bindViewProjection(effect);
  102205. var reflectionTexture = this._reflectionTexture;
  102206. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102207. // Texture uniforms
  102208. if (scene.texturesEnabled) {
  102209. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102210. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102211. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102212. }
  102213. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102214. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102215. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102216. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102217. }
  102218. }
  102219. if (this.shadowLevel > 0) {
  102220. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102221. }
  102222. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102223. // Point size
  102224. if (this.pointsCloud) {
  102225. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102226. }
  102227. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102228. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102229. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102230. }
  102231. else {
  102232. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102233. }
  102234. }
  102235. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102236. // Textures
  102237. if (scene.texturesEnabled) {
  102238. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102239. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102240. }
  102241. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102242. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102243. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102244. }
  102245. else if (!defines.REFLECTIONBLUR) {
  102246. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102247. }
  102248. else {
  102249. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102250. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102251. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102252. }
  102253. if (defines.REFLECTIONFRESNEL) {
  102254. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102255. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102256. }
  102257. }
  102258. }
  102259. // Clip plane
  102260. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102261. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102262. }
  102263. if (mustRebind || !this.isFrozen) {
  102264. if (scene.lightsEnabled) {
  102265. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102266. }
  102267. // View
  102268. this.bindView(effect);
  102269. // Fog
  102270. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102271. // image processing
  102272. if (this._imageProcessingConfiguration) {
  102273. this._imageProcessingConfiguration.bind(this._activeEffect);
  102274. }
  102275. }
  102276. this._uniformBuffer.update();
  102277. this._afterBind(mesh, this._activeEffect);
  102278. };
  102279. /**
  102280. * Dispose the material.
  102281. * @param forceDisposeEffect Force disposal of the associated effect.
  102282. * @param forceDisposeTextures Force disposal of the associated textures.
  102283. */
  102284. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102285. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102286. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102287. if (forceDisposeTextures) {
  102288. if (this.diffuseTexture) {
  102289. this.diffuseTexture.dispose();
  102290. }
  102291. if (this.reflectionTexture) {
  102292. this.reflectionTexture.dispose();
  102293. }
  102294. }
  102295. this._renderTargets.dispose();
  102296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102298. }
  102299. _super.prototype.dispose.call(this, forceDisposeEffect);
  102300. };
  102301. /**
  102302. * Clones the material.
  102303. * @param name The cloned name.
  102304. * @returns The cloned material.
  102305. */
  102306. BackgroundMaterial.prototype.clone = function (name) {
  102307. var _this = this;
  102308. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102309. };
  102310. /**
  102311. * Serializes the current material to its JSON representation.
  102312. * @returns The JSON representation.
  102313. */
  102314. BackgroundMaterial.prototype.serialize = function () {
  102315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102316. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102317. return serializationObject;
  102318. };
  102319. /**
  102320. * Gets the class name of the material
  102321. * @returns "BackgroundMaterial"
  102322. */
  102323. BackgroundMaterial.prototype.getClassName = function () {
  102324. return "BackgroundMaterial";
  102325. };
  102326. /**
  102327. * Parse a JSON input to create back a background material.
  102328. * @param source The JSON data to parse
  102329. * @param scene The scene to create the parsed material in
  102330. * @param rootUrl The root url of the assets the material depends upon
  102331. * @returns the instantiated BackgroundMaterial.
  102332. */
  102333. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102334. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102335. };
  102336. /**
  102337. * Standard reflectance value at parallel view angle.
  102338. */
  102339. BackgroundMaterial.StandardReflectance0 = 0.05;
  102340. /**
  102341. * Standard reflectance value at grazing angle.
  102342. */
  102343. BackgroundMaterial.StandardReflectance90 = 0.5;
  102344. __decorate([
  102345. BABYLON.serializeAsColor3()
  102346. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102347. __decorate([
  102348. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102349. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102350. __decorate([
  102351. BABYLON.serializeAsColor3()
  102352. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102353. __decorate([
  102354. BABYLON.serialize()
  102355. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102356. __decorate([
  102357. BABYLON.serialize()
  102358. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102359. __decorate([
  102360. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102361. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102362. __decorate([
  102363. BABYLON.serializeAsTexture()
  102364. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102365. __decorate([
  102366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102367. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102368. __decorate([
  102369. BABYLON.serialize()
  102370. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102371. __decorate([
  102372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102373. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102374. __decorate([
  102375. BABYLON.serializeAsTexture()
  102376. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102377. __decorate([
  102378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102379. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102380. __decorate([
  102381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102382. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102383. __decorate([
  102384. BABYLON.serialize()
  102385. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102386. __decorate([
  102387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102388. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102389. __decorate([
  102390. BABYLON.serializeAsVector3()
  102391. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102392. __decorate([
  102393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102394. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102395. __decorate([
  102396. BABYLON.serialize()
  102397. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102398. __decorate([
  102399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102400. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102401. __decorate([
  102402. BABYLON.serialize()
  102403. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102404. __decorate([
  102405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102406. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102407. __decorate([
  102408. BABYLON.serialize()
  102409. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102410. __decorate([
  102411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102412. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102413. __decorate([
  102414. BABYLON.serialize()
  102415. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102416. __decorate([
  102417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102418. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102419. __decorate([
  102420. BABYLON.serialize()
  102421. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102422. __decorate([
  102423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102424. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102425. __decorate([
  102426. BABYLON.serialize()
  102427. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102428. __decorate([
  102429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102430. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102431. __decorate([
  102432. BABYLON.serialize()
  102433. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102434. __decorate([
  102435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102436. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102437. __decorate([
  102438. BABYLON.serialize()
  102439. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102440. __decorate([
  102441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102442. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102443. __decorate([
  102444. BABYLON.serialize()
  102445. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102446. __decorate([
  102447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102448. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102449. __decorate([
  102450. BABYLON.serializeAsImageProcessingConfiguration()
  102451. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102452. return BackgroundMaterial;
  102453. }(BABYLON.PushMaterial));
  102454. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102455. })(BABYLON || (BABYLON = {}));
  102456. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102457. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102458. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102459. s = arguments[i];
  102460. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102461. t[p] = s[p];
  102462. }
  102463. return t;
  102464. };
  102465. var BABYLON;
  102466. (function (BABYLON) {
  102467. /**
  102468. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102469. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102470. * It also helps with the default setup of your imageProcessing configuration.
  102471. */
  102472. var EnvironmentHelper = /** @class */ (function () {
  102473. /**
  102474. * constructor
  102475. * @param options
  102476. * @param scene The scene to add the material to
  102477. */
  102478. function EnvironmentHelper(options, scene) {
  102479. var _this = this;
  102480. this._errorHandler = function (message, exception) {
  102481. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102482. };
  102483. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102484. this._scene = scene;
  102485. this.onErrorObservable = new BABYLON.Observable();
  102486. this._setupBackground();
  102487. this._setupImageProcessing();
  102488. }
  102489. /**
  102490. * Creates the default options for the helper.
  102491. */
  102492. EnvironmentHelper._getDefaultOptions = function () {
  102493. return {
  102494. createGround: true,
  102495. groundSize: 15,
  102496. groundTexture: this._groundTextureCDNUrl,
  102497. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102498. groundOpacity: 0.9,
  102499. enableGroundShadow: true,
  102500. groundShadowLevel: 0.5,
  102501. enableGroundMirror: false,
  102502. groundMirrorSizeRatio: 0.3,
  102503. groundMirrorBlurKernel: 64,
  102504. groundMirrorAmount: 1,
  102505. groundMirrorFresnelWeight: 1,
  102506. groundMirrorFallOffDistance: 0,
  102507. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102508. groundYBias: 0.00001,
  102509. createSkybox: true,
  102510. skyboxSize: 20,
  102511. skyboxTexture: this._skyboxTextureCDNUrl,
  102512. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102513. backgroundYRotation: 0,
  102514. sizeAuto: true,
  102515. rootPosition: BABYLON.Vector3.Zero(),
  102516. setupImageProcessing: true,
  102517. environmentTexture: this._environmentTextureCDNUrl,
  102518. cameraExposure: 0.8,
  102519. cameraContrast: 1.2,
  102520. toneMappingEnabled: true,
  102521. };
  102522. };
  102523. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102524. /**
  102525. * Gets the root mesh created by the helper.
  102526. */
  102527. get: function () {
  102528. return this._rootMesh;
  102529. },
  102530. enumerable: true,
  102531. configurable: true
  102532. });
  102533. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102534. /**
  102535. * Gets the skybox created by the helper.
  102536. */
  102537. get: function () {
  102538. return this._skybox;
  102539. },
  102540. enumerable: true,
  102541. configurable: true
  102542. });
  102543. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102544. /**
  102545. * Gets the skybox texture created by the helper.
  102546. */
  102547. get: function () {
  102548. return this._skyboxTexture;
  102549. },
  102550. enumerable: true,
  102551. configurable: true
  102552. });
  102553. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102554. /**
  102555. * Gets the skybox material created by the helper.
  102556. */
  102557. get: function () {
  102558. return this._skyboxMaterial;
  102559. },
  102560. enumerable: true,
  102561. configurable: true
  102562. });
  102563. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102564. /**
  102565. * Gets the ground mesh created by the helper.
  102566. */
  102567. get: function () {
  102568. return this._ground;
  102569. },
  102570. enumerable: true,
  102571. configurable: true
  102572. });
  102573. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102574. /**
  102575. * Gets the ground texture created by the helper.
  102576. */
  102577. get: function () {
  102578. return this._groundTexture;
  102579. },
  102580. enumerable: true,
  102581. configurable: true
  102582. });
  102583. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102584. /**
  102585. * Gets the ground mirror created by the helper.
  102586. */
  102587. get: function () {
  102588. return this._groundMirror;
  102589. },
  102590. enumerable: true,
  102591. configurable: true
  102592. });
  102593. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102594. /**
  102595. * Gets the ground mirror render list to helps pushing the meshes
  102596. * you wish in the ground reflection.
  102597. */
  102598. get: function () {
  102599. if (this._groundMirror) {
  102600. return this._groundMirror.renderList;
  102601. }
  102602. return null;
  102603. },
  102604. enumerable: true,
  102605. configurable: true
  102606. });
  102607. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102608. /**
  102609. * Gets the ground material created by the helper.
  102610. */
  102611. get: function () {
  102612. return this._groundMaterial;
  102613. },
  102614. enumerable: true,
  102615. configurable: true
  102616. });
  102617. /**
  102618. * Updates the background according to the new options
  102619. * @param options
  102620. */
  102621. EnvironmentHelper.prototype.updateOptions = function (options) {
  102622. var newOptions = __assign({}, this._options, options);
  102623. if (this._ground && !newOptions.createGround) {
  102624. this._ground.dispose();
  102625. this._ground = null;
  102626. }
  102627. if (this._groundMaterial && !newOptions.createGround) {
  102628. this._groundMaterial.dispose();
  102629. this._groundMaterial = null;
  102630. }
  102631. if (this._groundTexture) {
  102632. if (this._options.groundTexture != newOptions.groundTexture) {
  102633. this._groundTexture.dispose();
  102634. this._groundTexture = null;
  102635. }
  102636. }
  102637. if (this._skybox && !newOptions.createSkybox) {
  102638. this._skybox.dispose();
  102639. this._skybox = null;
  102640. }
  102641. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102642. this._skyboxMaterial.dispose();
  102643. this._skyboxMaterial = null;
  102644. }
  102645. if (this._skyboxTexture) {
  102646. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102647. this._skyboxTexture.dispose();
  102648. this._skyboxTexture = null;
  102649. }
  102650. }
  102651. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102652. this._groundMirror.dispose();
  102653. this._groundMirror = null;
  102654. }
  102655. if (this._scene.environmentTexture) {
  102656. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102657. this._scene.environmentTexture.dispose();
  102658. }
  102659. }
  102660. this._options = newOptions;
  102661. this._setupBackground();
  102662. this._setupImageProcessing();
  102663. };
  102664. /**
  102665. * Sets the primary color of all the available elements.
  102666. * @param color the main color to affect to the ground and the background
  102667. */
  102668. EnvironmentHelper.prototype.setMainColor = function (color) {
  102669. if (this.groundMaterial) {
  102670. this.groundMaterial.primaryColor = color;
  102671. }
  102672. if (this.skyboxMaterial) {
  102673. this.skyboxMaterial.primaryColor = color;
  102674. }
  102675. if (this.groundMirror) {
  102676. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102677. }
  102678. };
  102679. /**
  102680. * Setup the image processing according to the specified options.
  102681. */
  102682. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102683. if (this._options.setupImageProcessing) {
  102684. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102685. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102686. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102687. this._setupEnvironmentTexture();
  102688. }
  102689. };
  102690. /**
  102691. * Setup the environment texture according to the specified options.
  102692. */
  102693. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102694. if (this._scene.environmentTexture) {
  102695. return;
  102696. }
  102697. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102698. this._scene.environmentTexture = this._options.environmentTexture;
  102699. return;
  102700. }
  102701. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102702. this._scene.environmentTexture = environmentTexture;
  102703. };
  102704. /**
  102705. * Setup the background according to the specified options.
  102706. */
  102707. EnvironmentHelper.prototype._setupBackground = function () {
  102708. if (!this._rootMesh) {
  102709. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102710. }
  102711. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102712. var sceneSize = this._getSceneSize();
  102713. if (this._options.createGround) {
  102714. this._setupGround(sceneSize);
  102715. this._setupGroundMaterial();
  102716. this._setupGroundDiffuseTexture();
  102717. if (this._options.enableGroundMirror) {
  102718. this._setupGroundMirrorTexture(sceneSize);
  102719. }
  102720. this._setupMirrorInGroundMaterial();
  102721. }
  102722. if (this._options.createSkybox) {
  102723. this._setupSkybox(sceneSize);
  102724. this._setupSkyboxMaterial();
  102725. this._setupSkyboxReflectionTexture();
  102726. }
  102727. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102728. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102729. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102730. };
  102731. /**
  102732. * Get the scene sizes according to the setup.
  102733. */
  102734. EnvironmentHelper.prototype._getSceneSize = function () {
  102735. var _this = this;
  102736. var groundSize = this._options.groundSize;
  102737. var skyboxSize = this._options.skyboxSize;
  102738. var rootPosition = this._options.rootPosition;
  102739. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102740. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102741. }
  102742. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102743. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102744. });
  102745. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102746. if (this._options.sizeAuto) {
  102747. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102748. this._scene.activeCamera.upperRadiusLimit) {
  102749. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102750. skyboxSize = groundSize;
  102751. }
  102752. var sceneDiagonalLenght = sceneDiagonal.length();
  102753. if (sceneDiagonalLenght > groundSize) {
  102754. groundSize = sceneDiagonalLenght * 2;
  102755. skyboxSize = groundSize;
  102756. }
  102757. // 10 % bigger.
  102758. groundSize *= 1.1;
  102759. skyboxSize *= 1.5;
  102760. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102761. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102762. }
  102763. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102764. };
  102765. /**
  102766. * Setup the ground according to the specified options.
  102767. */
  102768. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102769. var _this = this;
  102770. if (!this._ground || this._ground.isDisposed()) {
  102771. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102772. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102773. this._ground.parent = this._rootMesh;
  102774. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102775. }
  102776. this._ground.receiveShadows = this._options.enableGroundShadow;
  102777. };
  102778. /**
  102779. * Setup the ground material according to the specified options.
  102780. */
  102781. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102782. if (!this._groundMaterial) {
  102783. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102784. }
  102785. this._groundMaterial.alpha = this._options.groundOpacity;
  102786. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102787. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102788. this._groundMaterial.primaryColor = this._options.groundColor;
  102789. this._groundMaterial.useRGBColor = false;
  102790. this._groundMaterial.enableNoise = true;
  102791. if (this._ground) {
  102792. this._ground.material = this._groundMaterial;
  102793. }
  102794. };
  102795. /**
  102796. * Setup the ground diffuse texture according to the specified options.
  102797. */
  102798. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102799. if (!this._groundMaterial) {
  102800. return;
  102801. }
  102802. if (this._groundTexture) {
  102803. return;
  102804. }
  102805. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102806. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102807. return;
  102808. }
  102809. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102810. diffuseTexture.gammaSpace = false;
  102811. diffuseTexture.hasAlpha = true;
  102812. this._groundMaterial.diffuseTexture = diffuseTexture;
  102813. };
  102814. /**
  102815. * Setup the ground mirror texture according to the specified options.
  102816. */
  102817. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102818. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102819. if (!this._groundMirror) {
  102820. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102821. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102822. this._groundMirror.anisotropicFilteringLevel = 1;
  102823. this._groundMirror.wrapU = wrapping;
  102824. this._groundMirror.wrapV = wrapping;
  102825. this._groundMirror.gammaSpace = false;
  102826. if (this._groundMirror.renderList) {
  102827. for (var i = 0; i < this._scene.meshes.length; i++) {
  102828. var mesh = this._scene.meshes[i];
  102829. if (mesh !== this._ground &&
  102830. mesh !== this._skybox &&
  102831. mesh !== this._rootMesh) {
  102832. this._groundMirror.renderList.push(mesh);
  102833. }
  102834. }
  102835. }
  102836. }
  102837. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102838. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102839. };
  102840. /**
  102841. * Setup the ground to receive the mirror texture.
  102842. */
  102843. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102844. if (this._groundMaterial) {
  102845. this._groundMaterial.reflectionTexture = this._groundMirror;
  102846. this._groundMaterial.reflectionFresnel = true;
  102847. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102848. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102849. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102850. }
  102851. };
  102852. /**
  102853. * Setup the skybox according to the specified options.
  102854. */
  102855. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102856. var _this = this;
  102857. if (!this._skybox || this._skybox.isDisposed()) {
  102858. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102859. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102860. }
  102861. this._skybox.parent = this._rootMesh;
  102862. };
  102863. /**
  102864. * Setup the skybox material according to the specified options.
  102865. */
  102866. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102867. if (!this._skybox) {
  102868. return;
  102869. }
  102870. if (!this._skyboxMaterial) {
  102871. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102872. }
  102873. this._skyboxMaterial.useRGBColor = false;
  102874. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102875. this._skyboxMaterial.enableNoise = true;
  102876. this._skybox.material = this._skyboxMaterial;
  102877. };
  102878. /**
  102879. * Setup the skybox reflection texture according to the specified options.
  102880. */
  102881. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102882. if (!this._skyboxMaterial) {
  102883. return;
  102884. }
  102885. if (this._skyboxTexture) {
  102886. return;
  102887. }
  102888. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102889. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102890. return;
  102891. }
  102892. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102893. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102894. this._skyboxTexture.gammaSpace = false;
  102895. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102896. };
  102897. /**
  102898. * Dispose all the elements created by the Helper.
  102899. */
  102900. EnvironmentHelper.prototype.dispose = function () {
  102901. if (this._groundMaterial) {
  102902. this._groundMaterial.dispose(true, true);
  102903. }
  102904. if (this._skyboxMaterial) {
  102905. this._skyboxMaterial.dispose(true, true);
  102906. }
  102907. this._rootMesh.dispose(false);
  102908. };
  102909. /**
  102910. * Default ground texture URL.
  102911. */
  102912. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102913. /**
  102914. * Default skybox texture URL.
  102915. */
  102916. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102917. /**
  102918. * Default environment texture URL.
  102919. */
  102920. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102921. return EnvironmentHelper;
  102922. }());
  102923. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102924. })(BABYLON || (BABYLON = {}));
  102925. //# sourceMappingURL=babylon.environmentHelper.js.map
  102926. var BABYLON;
  102927. (function (BABYLON) {
  102928. /** Internal class used to store shapes for emitters */
  102929. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102930. function ParticleSystemSetEmitterCreationOptions() {
  102931. }
  102932. return ParticleSystemSetEmitterCreationOptions;
  102933. }());
  102934. /**
  102935. * Represents a set of particle systems working together to create a specific effect
  102936. */
  102937. var ParticleSystemSet = /** @class */ (function () {
  102938. function ParticleSystemSet() {
  102939. /**
  102940. * Gets the particle system list
  102941. */
  102942. this.systems = new Array();
  102943. }
  102944. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102945. /**
  102946. * Gets the emitter node used with this set
  102947. */
  102948. get: function () {
  102949. return this._emitterNode;
  102950. },
  102951. enumerable: true,
  102952. configurable: true
  102953. });
  102954. /**
  102955. * Creates a new emitter mesh as a sphere
  102956. * @param options defines the options used to create the sphere
  102957. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102958. * @param scene defines the hosting scene
  102959. */
  102960. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102961. if (this._emitterNode) {
  102962. this._emitterNode.dispose();
  102963. }
  102964. this._emitterCreationOptions = {
  102965. kind: "Sphere",
  102966. options: options,
  102967. renderingGroupId: renderingGroupId
  102968. };
  102969. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102970. emitterMesh.renderingGroupId = renderingGroupId;
  102971. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102972. material.emissiveColor = options.color;
  102973. emitterMesh.material = material;
  102974. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102975. var system = _a[_i];
  102976. system.emitter = emitterMesh;
  102977. }
  102978. this._emitterNode = emitterMesh;
  102979. };
  102980. /**
  102981. * Starts all particle systems of the set
  102982. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102983. */
  102984. ParticleSystemSet.prototype.start = function (emitter) {
  102985. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102986. var system = _a[_i];
  102987. if (emitter) {
  102988. system.emitter = emitter;
  102989. }
  102990. system.start();
  102991. }
  102992. };
  102993. /**
  102994. * Release all associated resources
  102995. */
  102996. ParticleSystemSet.prototype.dispose = function () {
  102997. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102998. var system = _a[_i];
  102999. system.dispose();
  103000. }
  103001. this.systems = [];
  103002. if (this._emitterNode) {
  103003. this._emitterNode.dispose();
  103004. this._emitterNode = null;
  103005. }
  103006. };
  103007. /**
  103008. * Serialize the set into a JSON compatible object
  103009. * @returns a JSON compatible representation of the set
  103010. */
  103011. ParticleSystemSet.prototype.serialize = function () {
  103012. var result = {};
  103013. result.systems = [];
  103014. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103015. var system = _a[_i];
  103016. result.systems.push(system.serialize());
  103017. }
  103018. if (this._emitterNode) {
  103019. result.emitter = this._emitterCreationOptions;
  103020. }
  103021. return result;
  103022. };
  103023. /**
  103024. * Parse a new ParticleSystemSet from a serialized source
  103025. * @param data defines a JSON compatible representation of the set
  103026. * @param scene defines the hosting scene
  103027. * @param gpu defines if we want GPU particles or CPU particles
  103028. * @returns a new ParticleSystemSet
  103029. */
  103030. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103031. if (gpu === void 0) { gpu = false; }
  103032. var result = new ParticleSystemSet();
  103033. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103034. scene = scene || BABYLON.Engine.LastCreatedScene;
  103035. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103036. var system = _a[_i];
  103037. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103038. }
  103039. if (data.emitter) {
  103040. var options = data.emitter.options;
  103041. switch (data.emitter.kind) {
  103042. case "Sphere":
  103043. result.setEmitterAsSphere({
  103044. diameter: options.diameter,
  103045. segments: options.segments,
  103046. color: BABYLON.Color3.FromArray(options.color)
  103047. }, data.emitter.renderingGroupId, scene);
  103048. break;
  103049. }
  103050. }
  103051. return result;
  103052. };
  103053. return ParticleSystemSet;
  103054. }());
  103055. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103056. })(BABYLON || (BABYLON = {}));
  103057. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103058. var BABYLON;
  103059. (function (BABYLON) {
  103060. /**
  103061. * This class is made for on one-liner static method to help creating particle system set.
  103062. */
  103063. var ParticleHelper = /** @class */ (function () {
  103064. function ParticleHelper() {
  103065. }
  103066. /**
  103067. * This is the main static method (one-liner) of this helper to create different particle systems
  103068. * @param type This string represents the type to the particle system to create
  103069. * @param scene The scene where the particle system should live
  103070. * @param gpu If the system will use gpu
  103071. * @returns the ParticleSystemSet created
  103072. */
  103073. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103074. if (gpu === void 0) { gpu = false; }
  103075. if (!scene) {
  103076. scene = BABYLON.Engine.LastCreatedScene;
  103077. ;
  103078. }
  103079. var token = {};
  103080. scene._addPendingData(token);
  103081. return new Promise(function (resolve, reject) {
  103082. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103083. scene._removePendingData(token);
  103084. return reject("Particle system with GPU is not supported.");
  103085. }
  103086. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103087. scene._removePendingData(token);
  103088. var newData = JSON.parse(data.toString());
  103089. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103090. }, undefined, undefined, undefined, function (req, exception) {
  103091. scene._removePendingData(token);
  103092. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103093. });
  103094. });
  103095. };
  103096. /**
  103097. * Static function used to export a particle system to a ParticleSystemSet variable.
  103098. * Please note that the emitter shape is not exported
  103099. * @param system defines the particle systems to export
  103100. */
  103101. ParticleHelper.ExportSet = function (systems) {
  103102. var set = new BABYLON.ParticleSystemSet();
  103103. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103104. var system = systems_1[_i];
  103105. set.systems.push(system);
  103106. }
  103107. return set;
  103108. };
  103109. /**
  103110. * Gets or sets base Assets URL
  103111. */
  103112. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103113. return ParticleHelper;
  103114. }());
  103115. BABYLON.ParticleHelper = ParticleHelper;
  103116. })(BABYLON || (BABYLON = {}));
  103117. //# sourceMappingURL=babylon.particleHelper.js.map
  103118. var BABYLON;
  103119. (function (BABYLON) {
  103120. /**
  103121. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103122. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103123. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103124. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103125. */
  103126. var VideoDome = /** @class */ (function (_super) {
  103127. __extends(VideoDome, _super);
  103128. /**
  103129. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103130. * @param name Element's name, child elements will append suffixes for their own names.
  103131. * @param urlsOrVideo defines the url(s) or the video element to use
  103132. * @param options An object containing optional or exposed sub element properties
  103133. */
  103134. function VideoDome(name, urlsOrVideo, options, scene) {
  103135. var _this = _super.call(this, name, scene) || this;
  103136. _this._useDirectMapping = false;
  103137. // set defaults and manage values
  103138. name = name || "videoDome";
  103139. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103140. options.clickToPlay = Boolean(options.clickToPlay);
  103141. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103142. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103143. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103144. if (options.useDirectMapping === undefined) {
  103145. _this._useDirectMapping = true;
  103146. }
  103147. else {
  103148. _this._useDirectMapping = options.useDirectMapping;
  103149. }
  103150. // create
  103151. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103152. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103153. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103154. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103155. // configure material
  103156. material.useEquirectangularFOV = true;
  103157. material.fovMultiplier = 1.0;
  103158. material.opacityFresnel = false;
  103159. if (_this._useDirectMapping) {
  103160. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103161. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103162. material.diffuseTexture = texture;
  103163. }
  103164. else {
  103165. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103166. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103167. material.reflectionTexture = texture;
  103168. }
  103169. // configure mesh
  103170. _this._mesh.material = material;
  103171. _this._mesh.parent = _this;
  103172. // optional configuration
  103173. if (options.clickToPlay) {
  103174. scene.onPointerUp = function () {
  103175. _this._videoTexture.video.play();
  103176. };
  103177. }
  103178. return _this;
  103179. }
  103180. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103181. /**
  103182. * Gets the video texture being displayed on the sphere
  103183. */
  103184. get: function () {
  103185. return this._videoTexture;
  103186. },
  103187. enumerable: true,
  103188. configurable: true
  103189. });
  103190. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103191. /**
  103192. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103193. * Also see the options.resolution property.
  103194. */
  103195. get: function () {
  103196. return this._material.fovMultiplier;
  103197. },
  103198. set: function (value) {
  103199. this._material.fovMultiplier = value;
  103200. },
  103201. enumerable: true,
  103202. configurable: true
  103203. });
  103204. /**
  103205. * Releases resources associated with this node.
  103206. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103207. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103208. */
  103209. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103210. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103211. this._videoTexture.dispose();
  103212. this._mesh.dispose();
  103213. this._material.dispose();
  103214. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103215. };
  103216. return VideoDome;
  103217. }(BABYLON.Node));
  103218. BABYLON.VideoDome = VideoDome;
  103219. })(BABYLON || (BABYLON = {}));
  103220. //# sourceMappingURL=babylon.videoDome.js.map
  103221. var BABYLON;
  103222. (function (BABYLON) {
  103223. /**
  103224. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103225. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103226. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103227. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103228. */
  103229. var PhotoDome = /** @class */ (function (_super) {
  103230. __extends(PhotoDome, _super);
  103231. /**
  103232. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103233. * @param name Element's name, child elements will append suffixes for their own names.
  103234. * @param urlsOfPhoto define the url of the photo to display
  103235. * @param options An object containing optional or exposed sub element properties
  103236. */
  103237. function PhotoDome(name, urlOfPhoto, options, scene) {
  103238. var _this = _super.call(this, name, scene) || this;
  103239. _this._useDirectMapping = false;
  103240. // set defaults and manage values
  103241. name = name || "photoDome";
  103242. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103243. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103244. if (options.useDirectMapping === undefined) {
  103245. _this._useDirectMapping = true;
  103246. }
  103247. else {
  103248. _this._useDirectMapping = options.useDirectMapping;
  103249. }
  103250. // create
  103251. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103252. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103253. // configure material
  103254. material.opacityFresnel = false;
  103255. material.useEquirectangularFOV = true;
  103256. material.fovMultiplier = 1.0;
  103257. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103258. // configure mesh
  103259. _this._mesh.material = material;
  103260. _this._mesh.parent = _this;
  103261. return _this;
  103262. }
  103263. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103264. /**
  103265. * Gets or sets the texture being displayed on the sphere
  103266. */
  103267. get: function () {
  103268. return this._photoTexture;
  103269. },
  103270. set: function (value) {
  103271. if (this._photoTexture === value) {
  103272. return;
  103273. }
  103274. this._photoTexture = value;
  103275. if (this._useDirectMapping) {
  103276. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103277. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103278. this._material.diffuseTexture = this._photoTexture;
  103279. }
  103280. else {
  103281. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103282. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103283. this._material.reflectionTexture = this._photoTexture;
  103284. }
  103285. },
  103286. enumerable: true,
  103287. configurable: true
  103288. });
  103289. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103290. /**
  103291. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103292. * Also see the options.resolution property.
  103293. */
  103294. get: function () {
  103295. return this._material.fovMultiplier;
  103296. },
  103297. set: function (value) {
  103298. this._material.fovMultiplier = value;
  103299. },
  103300. enumerable: true,
  103301. configurable: true
  103302. });
  103303. /**
  103304. * Releases resources associated with this node.
  103305. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103306. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103307. */
  103308. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103309. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103310. this._photoTexture.dispose();
  103311. this._mesh.dispose();
  103312. this._material.dispose();
  103313. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103314. };
  103315. return PhotoDome;
  103316. }(BABYLON.Node));
  103317. BABYLON.PhotoDome = PhotoDome;
  103318. })(BABYLON || (BABYLON = {}));
  103319. //# sourceMappingURL=babylon.photoDome.js.map
  103320. 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\nvPositionUVW=positionUpdated;\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\nvPositionUVW=positionUpdated;\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;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\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(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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\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#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\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 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 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 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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\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 BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\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;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\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;\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","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}","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}","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;\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;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\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\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\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}","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}","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\nvPositionUVW=position;\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"};
  103321. 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","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","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};\n#endif\n#ifdef 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;\n#endif\n#ifdef 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 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\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\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","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","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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef 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#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if 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 vec3 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 vec3 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 vec3 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#ifdef USEPHYSICALLIGHTFALLOFF\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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*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*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,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*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*attenuation;\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}","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};","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","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};"};
  103322. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103323. globalObject["BABYLON"] = BABYLON;
  103324. //backwards compatibility
  103325. if(typeof earcut !== 'undefined') {
  103326. globalObject["Earcut"] = {
  103327. earcut: earcut
  103328. };
  103329. }
  103330. return BABYLON;
  103331. });